Search code examples
java-8comparable

thenComparing vs sort


Are there any differences (e.g. performance, ordering) of the two versions:

version 1:

mylist.sort(myComparator.sort_item);
mylist.sort(myComparator.sort_post);

version 2:

// java 8
mylist.sort(myComparator.sort_item
            .thenComparing(myComparator.sort_post));

Solution

  • From the Java 8 API documentation:

    [thenComparing] Returns a lexicographic-order comparator with another comparator. If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

    That means the second comparator is only used if the first one returns 0 (the elements are equal). So in practice it should be faster in most cases then calling sort twice.

    In theory, if the sorting algorithm is of time complexity C, then calling it twice will still be C (constant multiplication doesn't matter) to the complexity of both sorting methods is the same.