0

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

Kai
  • 5,850
  • 13
  • 43
  • 63
Vinoth Sankar
  • 53
  • 1
  • 9

2 Answers2

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
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