Is it possible to iterate a Collection parallel in Java. I'm looking for something like c# Parallel.ForEach
in System.Threading.Tasks
-Namespace
Asked
Active
Viewed 703 times
0

Kai
- 5,850
- 13
- 43
- 63

Vinoth Sankar
- 53
- 1
- 9
-
2Java8: `collection.stream().parallel().forEach(...)` – Konstantin Yovkov Oct 28 '15 at 11:51
2 Answers
2
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

Community
- 1
- 1

Sleiman Jneidi
- 22,907
- 14
- 56
- 77
-
2Indeed. Be very careful about using `parallel()`, it has a lot of caveats and shouldn't be used without fully understanding what it does. – Kayaman Oct 28 '15 at 12:00
-
@Sleiman: I'm using Java 1.7 Any other way to achieve it in Java 1.7 – Vinoth Sankar Oct 28 '15 at 12:29
-
@VinothSankar probably RxJava is the best, but your code wouldn't be concise – Sleiman Jneidi Oct 28 '15 at 12:33
1
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();
});

wadda_wadda
- 966
- 1
- 8
- 29