-1

If I want to add elements from a stream to a set using stream().forEach(e->{set.add(e)}, would it have any problems? or am i supposed to use forEachOrdered() thank you.

2 Answers2

0

It doesn’t make any difference until you use stream.paralle().foreach or foreachordered(). However since you are adding in set the items in the set may not be ordered. Refer to this link for details to understand difference between these two.

Ravik
  • 694
  • 7
  • 12
0

As you are using a set, the use of forEach or forEachOrdered does not matter anyway.

As per JournalDev JournalDev:

"Java Set is NOT an ordered collection, it’s elements does NOT have a particular order. Java Set does NOT provide control over the position where you can insert an element. You cannot access elements by their index and also search elements in the list."

If you were using Lists then the case would've been different depending upon the following:

  1. If you are using streams and not parallel streams, the end result would still be the same.
  2. If you are using parallel streams, the order will most likely differ if you use parallel streams instead of streams.

Consider the following example:

List<Integer> list = Arrays.asList(2, 4, 6, 8, 10);
System.out.println("forEach");
list.stream().parallel().forEach( System.out::println );
System.out.println();
System.out.println("forEachOrdered");
list.stream().parallel().forEachOrdered( System.out::println );

The output can be:

forEach
6
10
8
4
2
 
forEachOrdered
2
4
6
8
10
Jalaj Varshney
  • 131
  • 1
  • 9