For each element i in each list perform an operation. Elements can be processed in any order. For example in old java:
List<A> aList;
List<B> bList; // aList is larger than bList
for (int i=0; i<bList.size(), i++) {
aList.get(i).doSomethingWith(bList.get(i));
}
for (int j=i; j<aList.size(), j++) {
aList.get(j).doSomething();
}
Which is the best way to implement this with java.util.stream.Stream
so elements can be processed in parallel?
Parallel Streams. Any stream in Java can easily be transformed from sequential to parallel. We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection: List<Integer> listOfNumbers = Arrays.
The 'Stream' interface in Java, which was introduced in Java 8, is used to manipulate data collections in a declarative fashion. Stream interface can also be used to execute processes in parallel, without making the process too complicated.
If you need to combine more than two Streams, you can invoke the concat() method again from within the original invocation: Stream<String> combinedStream = Stream. concat( Stream. concat(collectionA.
You need to work on both lists in parallel so I don't think you can stream the lists themselves. However you can stream the indices and work on that:
IntStream.range(0, aList.size())
.parallel()
.forEach(i -> {
if (i < bList.size()) aList.get(i).doSomethingWith(bList.get(i));
else aList.get(i).doSomething();
});
Just because Stream
is new it does not mean that you should forget about all other tools Java provides. Even using these good old tools becomes smoother using Java 8:
List<A> aList;
List<B> bList; // aList is larger than bList
ExecutorService exec = Executors.newCachedThreadPool();
int a=aList.size(), b=bList.size();
assert a>b;
Future<?> f1=exec.submit(()->IntStream.range(0, b)
.parallel().forEach(i->aList.get(i).doSomethingWith(bList.get(i)))
);
Future<?> f2=exec.submit(()->aList.subList(b, a)
.stream().parallel().forEach(A::doSomething)
);
f1.get();
f2.get();
exec.shutdown();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With