fork download
  1. import java.util.Arrays;
  2. import java.util.Random;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.Future;
  7. import java.util.stream.IntStream;
  8.  
  9. class MedianFilter {
  10.  
  11. public static <T extends Comparable<T>> T[] getMedians(T[] data, int shoulder) {
  12. T[] result = Arrays.copyOf(data, data.length);
  13. IntStream.range(shoulder, data.length - shoulder).parallel().forEach(i -> result[i] = medianPoint(data, i, shoulder));
  14. return result;
  15. }
  16.  
  17. private static <T extends Comparable<T>> T medianPoint(T[] data, int index, int shoulder) {
  18. T[] window = Arrays.copyOfRange(data, index - shoulder, index + shoulder + 1);
  19. if (window.length != (shoulder * 2 + 1)) {
  20. throw new IllegalStateException("Illegal window size " + window.length);
  21. }
  22. Arrays.sort(window);
  23. return window[shoulder];
  24. }
  25.  
  26. public static void main(String[] args) throws InterruptedException, ExecutionException {
  27. Random rand = new Random(100);
  28. Integer[] data = rand.ints(10, 0, 20).boxed().toArray(s -> new Integer[s]);
  29. System.out.println(Arrays.toString(data));
  30. System.out.println(Arrays.toString(getMedians(data, 4)));
  31. Future<Integer[]> fut = medians(data, 4);
  32. System.out.println(Arrays.toString(fut.get()));
  33. }
  34.  
  35. public static <T extends Comparable<T>> Future<T[]> medians(T[] data, int shoulder) {
  36. ExecutorService service = Executors.newSingleThreadExecutor(r -> {
  37. Thread t = new Thread(r);
  38. t.setDaemon(true);
  39. return t;
  40. });
  41.  
  42. Future<T[]> fut = service.submit(() -> getMedians(data, shoulder));
  43. service.shutdown();
  44. return fut;
  45. }
  46.  
  47. }
Success #stdin #stdout 0.24s 321728KB
stdin
Standard input is empty
stdout
[15, 10, 14, 8, 11, 6, 16, 8, 3, 13]
[15, 10, 14, 8, 10, 10, 16, 8, 3, 13]
[15, 10, 14, 8, 10, 10, 16, 8, 3, 13]