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.
Asked
Active
Viewed 470 times
-1
-
2Neither. The preferred way is to use `Set<…> set = … .collect(Collectors.toSet());` – Holger Feb 04 '21 at 16:37
2 Answers
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:
- If you are using
streams
and notparallel streams
, the end result would still be the same. - If you are using parallel streams, the order will most likely differ if you use
parallel streams
instead ofstreams
.
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