-2

While learning lambda's, I found sorted method is not working as intended.

The following program is giving [1, 33, 2, 4, 5, 11] as an output, however I am expecting a sorted output.

Strange thing is when I replace the [33, 2, 1, 4, 5, 11] with [ 3, 1,2, 4, 5] every thing works fine and I got the sorted output as expected.

public class Test {
            public static void main(String[] args) {
            List<Integer> list = Arrays.asList(33, 2, 1, 4, 5, 11);
            Set<Integer> set = list.stream().sorted().collect(Collectors.toSet());
            System.out.println(set);
        }
      }

Please help me understand this behavior.

Sachin Sachdeva
  • 10,744
  • 2
  • 45
  • 108

1 Answers1

2

You should collect to a Collection which preserves ordering which a HashSet in role by the default implementation of toSet doesn't:

.collect(Collectors.toCollection(LinkedHashSet::new))
Naman
  • 21,685
  • 24
  • 196
  • 332
  • But why it is working for 3, 1,2, 4, 5 – Sachin Sachdeva Dec 03 '19 at 05:58
  • 4
    'Cos ... luck. Or more precisely, a deterministic but serendipitous ordering that is determined the way that `Integer:hashCode` is calculated + the way that the (default) `HashSet` is being populated. – Stephen C Dec 03 '19 at 06:03
  • 2
    @Joker That could just be a coincidence along with the fact as pointed by Stephen the hashcode implementation of the Integer. For one such experiment, you can remove the `sorted` operation with the input `3, 1,2, 4, 5` and verify the output if it would just remain the same as you find with the `sorted` operation. – Naman Dec 03 '19 at 06:08