Vinoth Sankar
Vinoth Sankar

Reputation: 53

How to parallely iterate a collection in java?

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

Upvotes: 0

Views: 714

Answers (2)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

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

Upvotes: 2

wadda_wadda
wadda_wadda

Reputation: 1004

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

Upvotes: 1

Related Questions