Java lambdas ((arg1, arg2) -> code;) are somewhat weirdly type inferred. Inference goes inside out, then outside in, then inside out again.

The reason is that java's functional typing system is based off of so-called functional interfaces. You don't, in java, just have an expression of type (int, int) -> String.

That explains why in java you can write listOfStrings.sort(Comparator.comparing(x -> x.length()));. Because, think about that line for a moment: How in the blazes is java allowing you to write x.length() there? j.l.Object doesn't have length(). Why does x? We never mentioned what type x is.

That's because java resolves inside-out first: Okay, we have a lambda. It will represent some type but we don't yet know what. For now we know: It's a lambda, and, it takes 1 argument.

So then javac scans Comparator.comparing and finds a few overloads. It can immediately eliminate some. Eventually only one remains: It takes a Function<T, U>, and returns a Comparator<T>. Okay, so I guess for now we go with T t -> t.length(). That isn't much help. Yet. We keep going: That is passed to .sort, which requires a Comparator<E>. That just kicks the can down the road; replacing one typevar with another, not useful. Let's keep going: That sort method is called on a on a List<String>. aha! Only a Comparator<String> is valid there, so I guess E is string! So let's apply that all the way back down - we go with String t -> t.length(). And that, finally, 'fits'. So java compiles this whole thing interpreting x -> x.length() as 'a Function<String, Comparable-to-self>. And then re-scans that lambda to ensure it makes sense in that context. Only now could e.g. a typo in length() be found as 'hey, that's not a method strings have'.

The problem with your code snippet that doesn't compile is that the compiler is limited in how far it can take this inside-out-outside-in process. It has to go too far and gives up. (It's a lot more complicated than this, but, you need to fully grok large swathes of the JLS to go any further).

Add some casts to 'help' the compiler and it works again:

Comparator<Edge> myComparator = Comparator.comparing(e -> e.a.x()).thenComparing(Comparator.<Edge>comparing(e -> e.b.x()));

Or add a (Comparator<Edge>) cast. The reason your other snippet does work is the local variable types serve as that 'type hint'.

Answer from rzwitserloot on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › guide to java comparator.comparing()
Guide to Java Comparator.comparing() | Baeldung
January 8, 2024 - @Test public void whenThenComparing_thenSortedByAgeName(){ Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge) .thenComparing(Employee::getName); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName)); }
🌐
Medium
medium.com › @AlexanderObregon › javas-comparator-thencomparing-method-explained-988e8f926a64
Java’s Comparator.thenComparing() Explained | Medium
November 6, 2024 - In this article, we’ll explore ... scenarios. The Comparator interface in Java provides a way to define the order in which elements of a collection should be arranged....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
3 weeks ago - Comparator<String> cmp = Comparator.comparingInt(String::length) .thenComparing(String.CASE_INSENSITIVE_ORDER);
🌐
How to do in Java
howtodoinjava.com › home › java sorting › java comparator thencomparing() example
Java Comparator thenComparing() Example - HowToDoInJava
August 30, 2022 - Java example of sorting a List of objects by multiple fields using Comparator.thenComparing() method. This method returns a lexicographic-order Comparator with another specified Comparator.
🌐
Blogger
javarevisited.blogspot.com › 2021 › 09 › comparator-comparing-thenComparing-example-java-.html
Java 8 Comparator comparing() and thenComparing() Example - Tutorial
May 24, 2023 - The key must be Comparable though like String, Integer, or any Java class which implements java.lang.Comparable interface, I mean the key must implement Comparable interface. Both comparing() and thenComparing() allows you to easily compare objects on any field as well as compare them on multiple fields by chaining comparators.
Top answer
1 of 1
5

Java lambdas ((arg1, arg2) -> code;) are somewhat weirdly type inferred. Inference goes inside out, then outside in, then inside out again.

The reason is that java's functional typing system is based off of so-called functional interfaces. You don't, in java, just have an expression of type (int, int) -> String.

That explains why in java you can write listOfStrings.sort(Comparator.comparing(x -> x.length()));. Because, think about that line for a moment: How in the blazes is java allowing you to write x.length() there? j.l.Object doesn't have length(). Why does x? We never mentioned what type x is.

That's because java resolves inside-out first: Okay, we have a lambda. It will represent some type but we don't yet know what. For now we know: It's a lambda, and, it takes 1 argument.

So then javac scans Comparator.comparing and finds a few overloads. It can immediately eliminate some. Eventually only one remains: It takes a Function<T, U>, and returns a Comparator<T>. Okay, so I guess for now we go with T t -> t.length(). That isn't much help. Yet. We keep going: That is passed to .sort, which requires a Comparator<E>. That just kicks the can down the road; replacing one typevar with another, not useful. Let's keep going: That sort method is called on a on a List<String>. aha! Only a Comparator<String> is valid there, so I guess E is string! So let's apply that all the way back down - we go with String t -> t.length(). And that, finally, 'fits'. So java compiles this whole thing interpreting x -> x.length() as 'a Function<String, Comparable-to-self>. And then re-scans that lambda to ensure it makes sense in that context. Only now could e.g. a typo in length() be found as 'hey, that's not a method strings have'.

The problem with your code snippet that doesn't compile is that the compiler is limited in how far it can take this inside-out-outside-in process. It has to go too far and gives up. (It's a lot more complicated than this, but, you need to fully grok large swathes of the JLS to go any further).

Add some casts to 'help' the compiler and it works again:

Comparator<Edge> myComparator = Comparator.comparing(e -> e.a.x()).thenComparing(Comparator.<Edge>comparing(e -> e.b.x()));

Or add a (Comparator<Edge>) cast. The reason your other snippet does work is the local variable types serve as that 'type hint'.

🌐
ConcretePage
concretepage.com › java › java-8 › java-comparator-thencomparing
Java Comparator.thenComparing - ConcretePage.com
Comparator.thenComparing method is introduced in Java 8. Comparator.thenComparing returns a lexicographic-order comparator that is called by a Comparator instance to sort the items using group of sort keys.
🌐
Tabnine
tabnine.com › home page › code › java › java.util.comparator
Java Examples & Tutorials of Comparator.thenComparing (java.util) | Tabnine
@Override public int compareTo(TotalRankSolverRankingWeight other) { return Comparator .comparingInt(TotalRankSolverRankingWeight::getBetterCount) .thenComparingInt(TotalRankSolverRankingWeight::getEqualCount) .thenComparingInt(TotalRankSolverRankingWeight::getLowerCount) .thenComparing(TotalRankSolverRankingWeight::getSolverBenchmarkResult, totalScoreSolverRankingComparator) // Tie-breaker .compare(this, other); }
Find elsewhere
🌐
Coderanch
coderanch.com › t › 756480 › java › Histogram-thenComparing-compiling
Histogram and thenComparing() not compiling (Java in General forum at Coderanch)
Carey Brown wrote:Honestly I don't know why this works except maybe you are declaring the type explicitly instead of the compiler having to infer it N-levels deep. Java uses the return type of comparingByKey() to determine what type thenComparing() should return.
Top answer
1 of 4
159

First, all the examples you say cause errors compile fine with the reference implementation (javac from JDK 8.) They also work fine in IntelliJ, so its quite possible the errors you're seeing are Eclipse-specific.

Your underlying question seems to be: "why does it stop working when I start chaining." The reason is, while lambda expressions and generic method invocations are poly expressions (their type is context-sensitive) when they appear as method parameters, when they appear instead as method receiver expressions, they are not.

When you say

Collections.sort(playlist1, comparing(p1 -> p1.getTitle()));

there is enough type information to solve for both the type argument of comparing() and the argument type p1. The comparing() call gets its target type from the signature of Collections.sort, so it is known comparing() must return a Comparator<Song>, and therefore p1 must be Song.

But when you start chaining:

Collections.sort(playlist1,
                 comparing(p1 -> p1.getTitle())
                     .thenComparing(p1 -> p1.getDuration())
                     .thenComparing(p1 -> p1.getArtist()));

now we've got a problem. We know that the compound expression comparing(...).thenComparing(...) has a target type of Comparator<Song>, but because the receiver expression for the chain, comparing(p -> p.getTitle()), is a generic method call, and we can't infer its type parameters from its other arguments, we're kind of out of luck. Since we don't know the type of this expression, we don't know that it has a thenComparing method, etc.

There are several ways to fix this, all of which involve injecting more type information so that the initial object in the chain can be properly typed. Here they are, in rough order of decreasing desirability and increasing intrusiveness:

  • Use an exact method reference (one with no overloads), like Song::getTitle. This then gives enough type information to infer the type variables for the comparing() call, and therefore give it a type, and therefore continue down the chain.
  • Use an explicit lambda (as you did in your example).
  • Provide a type witness for the comparing() call: Comparator.<Song, String>comparing(...).
  • Provide an explicit target type with a cast, by casting the receiver expression to Comparator<Song>.
2 of 4
29

The problem is type inferencing. Without adding a (Song s) to the first comparison, comparator.comparing doesn't know the type of the input so it defaults to Object.

You can fix this problem 1 of 3 ways:

  1. Use the new Java 8 method reference syntax

     Collections.sort(playlist,
                Comparator.comparing(Song::getTitle)
                .thenComparing(Song::getDuration)
                .thenComparing(Song::getArtist)
                );
    
  2. Pull out each comparison step into a local reference

      Comparator<Song> byName = (s1, s2) -> s1.getArtist().compareTo(s2.getArtist());
    
      Comparator<Song> byDuration = (s1, s2) -> Integer.compare(s1.getDuration(), s2.getDuration());
    
        Collections.sort(playlist,
                byName
                .thenComparing(byDuration)
                );
    

    EDIT

  3. Forcing the type returned by the Comparator (note you need both the input type and the comparison key type)

    sort(
      Comparator.<Song, String>comparing((s) -> s.getTitle())
                .thenComparing(p1 -> p1.getDuration())
                .thenComparing(p1 -> p1.getArtist())
                );
    

I think the "last" thenComparing syntax error is misleading you. It's actually a type problem with the whole chain, it's just the compiler only marking the end of the chain as a syntax error because that's when the final return type doesn't match I guess.

I'm not sure why List is doing a better inferencing job than Collection since it should do the same capture type but apparently not.

🌐
Coderanch
coderanch.com › t › 651485 › java › comparingDouble-thenComparing
comparingDouble and thenComparing (Features new in Java 8 forum at Coderanch)
thenComparingXXX() are to use in case you want to define an additional Comparison criteria if the elements in your stream are equal according - I will call it- to "main comparison" criteria. In other words, in your example your "main comparison" criteria seems to be the amount of a transaction.
🌐
Oracle
docs.oracle.com › javase › 10 › docs › api › java › util › Comparator.html
Comparator (Java SE 10 & JDK 10 )
Comparator<String> cmp = Comparator.comparingInt(String::length) .thenComparing(String.CASE_INSENSITIVE_ORDER);
🌐
Javabrahman
javabrahman.com › java-8 › the-complete-java-8-comparator-tutorial-with-examples
The Complete Java 8 Comparator Tutorial with examples
empNameComparator = Comparator.comparing(Employee::getName);[/su_note] Java 8 Comparator's thenComparing() method for multiple sort criteria Many-a-times we need to sort with multiple sort orders. I.e. on more than one attributes of an object. The second level sort order gets used if the first level sort criteria is indecisive.
🌐
Benchresources
benchresources.net › home › java › java 8 – thencomparing() method for custom/reverse sorting
Java 8 – thenComparing() method for custom/reverse sorting - BenchResources.Net
October 18, 2021 - default <U> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) Where · T is the type of element to be compared · keyExtractor is the function used to extract the sort key · U is the type of sort key · keyComparator is the Comparator used to compare the sort key · Exception :- Throws NullPointerException, if the argument is null · Check Java doc ·
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Comparator.html
Comparator (Java SE 11 & JDK 11 )
January 20, 2026 - Comparator<String> cmp = Comparator.comparingInt(String::length) .thenComparing(String.CASE_INSENSITIVE_ORDER);
🌐
Coderanch
coderanch.com › t › 656713 › java › Type-inferencing-Lambdas-chained-Comparators
Type inferencing with Lambdas and chained Comparators (Java in General forum at Coderanch)
I think that because if the first one is a cast, Java is using Object as the generic type: If I add getters and use a method reference, thenComparing doesn't need the cast: Of course with that approach, you could use a method reference for last name too making this a moot point.