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

1
  • 2
    Java8: collection.stream().parallel().forEach(...) Commented Oct 28, 2015 at 11:51

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Indeed. Be very careful about using parallel(), it has a lot of caveats and shouldn't be used without fully understanding what it does.
@Sleiman: I'm using Java 1.7 Any other way to achieve it in Java 1.7
@VinothSankar probably RxJava is the best, but your code wouldn't be concise
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(); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.