Does Distinct() After sorted() gives different result rather use independent stream?

42 Views Asked by At

I have used distenict() after sorted() and same on list stream both gives diff result

    List<String> list1 = Arrays.asList("aaaaa", "b", "lll", "kkk", "kkk");
    List<String> list2 = Arrays.asList("h", "kkk", "mmmm");

    List<String> list3 = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
    System.out.println("=======================================");
    list3.stream().distinct().sorted(Comparator.comparing(String::length)).forEach(System.out::println);
    ; // System.out.println(g);
    System.out.println("=======================================");
    list3.stream().distinct().forEach(System.out::println);
1

There are 1 best solutions below

0
Simulant On

I assume you are asking why your second call of distinct() in line

list3.stream().distinct().forEach(System.out::println);

does not print out the same result as the first time for the line

list3.stream().distinct().sorted(Comparator.comparing(String::length)).forEach(System.out::println);

This is because you are working on a stream of the elements from the list. First you take only distinct results from this stream and then you are sorting this stream before you are printing it.

All these operations happen only on the stream. They do not modify the backing list of the stream. So the order and content of the elements in the List stay the same.

So your second distinct stream happens on the same original not sorted list.