Is it possible to iterate a Collection parallel in Java. I'm looking for something like c# Parallel.ForEach in System.Threading.Tasks-Namespace
2 Answers
The Stream API in Java 1.8 was designed with parallelism in mind, so you can convert any Stream to a parallel stream. for example:
Stream.of(1,2,3,4,5,6,7).parallel().forEach(System.out::println); And In fact every Stream can be converted into a parallel one
Stream<Integer> parallel = stream.parallel(); And Collection provides a method that return a parallelStream.
Stream<Integer> parallel = Arrays.asList(1,2,3).parallelStream(); Now, this does not mean every operation can be efficiently parallelised, it depends on the nature of the source collection and the task you doing. Check this out
3 Comments
Kayaman
Indeed. Be very careful about using
parallel(), it has a lot of caveats and shouldn't be used without fully understanding what it does.Vinoth Sankar
@Sleiman: I'm using Java 1.7 Any other way to achieve it in Java 1.7
Sleiman Jneidi
@VinothSankar probably RxJava is the best, but your code wouldn't be concise
Assuming you're on Java 8, you should use streams. If you're not on Java 8, there's no baked-in equivalent.
sandwichCollection.parallelStream().forEach((sandwich) -> { sandwich.eat(); });
collection.stream().parallel().forEach(...)