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'.
Videos
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 thecomparing()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>.
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:
Use the new Java 8 method reference syntax
Collections.sort(playlist, Comparator.comparing(Song::getTitle) .thenComparing(Song::getDuration) .thenComparing(Song::getArtist) );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
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.
With Java 8:
Comparator.comparing((Person p)->p.firstName)
.thenComparing(p->p.lastName)
.thenComparingInt(p->p.age);
If you have accessor methods:
Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge);
If a class implements Comparable then such comparator may be used in compareTo method:
@Override
public int compareTo(Person o){
return Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge)
.compare(this, o);
}
You should implement Comparable <Person>. Assuming all fields will not be null (for simplicity sake), that age is an int, and compare ranking is first, last, age, the compareTo method is quite simple:
public int compareTo(Person other) {
int i = firstName.compareTo(other.firstName);
if (i != 0) return i;
i = lastName.compareTo(other.lastName);
if (i != 0) return i;
return Integer.compare(age, other.age);
}