11

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?

2 Answers 2

20

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();
    });
Sign up to request clarification or add additional context in comments.

Comments

6

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();

3 Comments

Good solution Holger, but I think assylias has proposed a better approach. Its cleaner and relies exclusively on the library for concurrency.
@Jose Gisbert: I don’t get the last sentence of your comment. Where does my solution depend on anything else than the “library for concurrency”? It’s pure Java standard API. The difference is that it does not need any conditional code whereas the few extra lines do not harm. But I didn’t want to trump assylias’ solution just complement it.
I'm sorry, when I said 'library' I meant java.util.stream package. I agree your solution makes use of Java standard API, for this reason I upvoted it. However, considering Stream already provides concurrency, I personally believe that using an Executor its redundant, but that's my opinion. Didn't mean to offend you @Holger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.