hi Tiam,
stream.sorted takes either no parameter, in which case the elements of the stream must implement Comparable and the sorting is done on that basis, or it takes a Comparator which then is used on the sorting.
In your code-snippets there are two Comparators mentioned:
1) a Comparator<
String> 'lengthComp' that compares strings on the basis of their lengths
2) a Comparator<String> in the form of a method-reference.
lengthComp is given with a lambda-expression:
and the second Comparator
is in fact this Comparator:
and it uses the natural ordering of Strings.
If you look at the api of the Comparator-class, you see that if you have the Comparators c1 and c2, then
is also a Comparator, that sorts its elements first according to c1, and in case two elements are equal with respect to this Comparator, another comparison is done based on the Comparator c2.
So,
is a Comparator that first sorts the elements on the basis of their lengths, and in case these lengths are the same, the elements are then sorted according to their natural ordering.
So, the list ["bb", "b", "aa", "a"] will become, after sorting with that Comparator: ["a", "b", "aa", "bb"]
If we sort that list only on the basis of the lengthComp-comparator, we would get: ["b", "a", "bb", "aa"]