Java Stream Collectors sort the given stream

Viewed 287

can you please let me know why below code returns the set sorted order given an unsorted array?

    Stream<Integer> s = Stream.of(2, 3, 1, 4, 5);

    Set<Integer> mySet = s.collect(Collectors.toSet());

    System.out.println(mySet);

O/p

1, 2, 3, 4, 5

This doesn't happen if I use List instead of Set. Also the sorting is not always correct when there are negative numbers in the input. Is there any inbuilt functionality to sort the Set?

2 Answers

This is just an accident and has nothing to do with Collector or Stream. On OpenJDK 11.0.2, I'm getting this (as Collector.toSet() is currently backed by HashSet):

Set<Integer> set = new HashSet<>();
set.add(2);
set.add(3);
set.add(1);
set.add(4);
set.add(5);
System.out.println(set); // [1, 2, 3, 4, 5]

But try this:

set.add(100);
System.out.println(set); // [1, 2, 3, 4, 100, 5]

It is really just an accident. A very curious one, indeed, which has to do with the Integer.hashCode() implementation (it's just the Integer.intValue() itself), and how this results in accidentally ordering HashSet elements for certain sets.

It is just a coincidence. The Set interface does not provide any ordering guarantees, but LinkedHashSet.

Related