Back to Intellij Community

ComparatorCombinators

java/java-impl/resources/inspectionDescriptions/ComparatorCombinators.html

2025.3-rc-2848 B
Original Source

Reports Comparator instances defined as lambda expressions that could be expressed using Comparator.comparing() calls. Chained comparisons which can be replaced by Comparator.thenComparing() expression are also reported.

Example:

myList.sort((person1, person2) -> person1.getName().compareTo(person2.getName()));

  myList2.sort((person1, person2) -> {
      int res = person1.first().compareTo(person2.first());
      if(res == 0) res = person1.second().compareTo(person2.second());
      if(res == 0) res = person1.third() - person2.third();
      return res;
  });

After the quick-fixes are applied:

myList.sort(Comparator.comparing(Person::getName));

  myList2.sort(Comparator.comparing(Person::first)
                         .thenComparing(Person::second)
                         .thenComparingInt(Person::third));