In Java8
, processing pairs of items in two parallel streams as below:
final List<Item> items = getItemList();
final int l = items.size();
List<String> results = Collections.synchronizedList(new ArrayList<String>());
IntStream.range(0, l - 1).parallel().forEach(
i -> {
Item item1 = items.get(i);
int x1 = item1.x;
IntStream.range(i + 1, l).parallel()
.forEach(j -> {
Item item2 = items.get(j);
int x2 = item2.x;
if (x1 + x2 < 200) return;
// code that writes to ConcurrentHashMap defined near results
if (x1 + x2 > 500) results.add(i + " " + j);
});
}
);
Each stream pair writes to ConcurrentHashMap
, and depending on certain conditions it may terminate the stream execution by calling return;
or it may write to a synchronized list.
I want to make streams return the results like return i + " " + j
and collect those results into a list strings outside. It should be partial as returning nothing must be supported (in case when x1 + x2 < 200
).
What would be the most time-efficient (fastest code) way to achieve that?