Java – use the stream to find objects in the list
See the English answer > why filter () after flatmap () is "not completely" lazy in Java streams? 6
// returns [i,j] where lists.get(i).get(j) equals o,or null if o is not present. public static int[] indices(List<? extends List<?>> lists,Object o) { return IntStream.range(0,lists.size()) .@R_670_2419@ed() .flatMap(i -> IntStream.range(0,lists.get(i).size()).mapToObj(j -> new int[]{i,j})) .parallel() .filter(a -> { System.out.println(Arrays.toString(a)); // For testing only return Objects.equals(o,lists.get(a[0]).get(a[1])); }) .findAny() .orElse(null); }
When I run the following code
List<List<String>> lists = Arrays.asList( Arrays.asList("A","B","C"),Arrays.asList("D","E","F","G"),Arrays.asList("H","I"),Collections.nCopies(5,"J") ); System.out.println("Indices are " + Arrays.toString(indices(lists,"J")));
The output is like this
[0,0] [0,1] [0,2] [3,0] [3,1] [3,3] [2,4] [1,0] [1,1] [2,1] [1,2] [1,3] Indices are [3,0]
In other words, the search continues even after the object is found Should it be a short circuit operation? What did I miss? In addition, what is the best way to take advantage of parallelism when iterating over lists or jagged arrays?
edit
According to @ Sotirios's answer, I got an output
Thread[ForkJoinPool.commonPool-worker-3,5,main] [3,0] Thread[main,main] [2,1] Thread[ForkJoinPool.commonPool-worker-1,main] [1,0] Thread[ForkJoinPool.commonPool-worker-1,2] Thread[ForkJoinPool.commonPool-worker-1,3] Thread[main,main] [0,1] Thread[ForkJoinPool.commonPool-worker-3,1] Thread[main,2] Thread[ForkJoinPool.commonPool-worker-3,3] Thread[ForkJoinPool.commonPool-worker-3,4] Indices are [3,0]
Please note that
Thread[ForkJoinPool.commonPool-worker-3,main]
Continue searching after finding the answer
Solution
Short circuit operation cannot guarantee that only as few elements are produced as required to produce results They may do so, but it is not necessary
The current implementation of flatmap is such that it always pushes the whole content of the sub stream downstream Therefore, even if your flow is not parallel, you can see that more elements flow through the flow than are required to meet findany