BufBills
BufBills

Reputation: 8103

Java 8 Stream multithreading

mylist.stream()
      .filter(m -> m.isokay() != null)
      .forEach(m -> m.dosomething()));

For this code, is it running on multiple threads? If not, how can I do it? I want each m.dosomething() to run on seperate threads to speed this work up.

Upvotes: 18

Views: 20621

Answers (1)

Makoto
Makoto

Reputation: 106430

Use parallelStream() to accomplish this. Note that the documentation says that it is "possibly parallel", so there's a chance that you could return a non-parallel stream. I would imagine those cases are rare, but be aware that it is in fact a limitation.

mylist.parallelStream()
      .filter(m -> m.isokay() != null)
      .forEach(m -> m.dosomething()));

Upvotes: 24

Related Questions