Videos
You could threat the result of indexOf as an unsigned integer. Then -1 would be the maximum value and be placed after the others.
This is probably the most readable way to do this (every index gets boxed though):
Comparator.comparing(ordering::indexOf, Integer::compareUnsigned)
Here is a faster alternative that avoids boxing:
Comparator.comparingInt(s -> ordering.indexOf(s) + Integer.MIN_VALUE)
I can only think of
final Comparator<String> orderingComparator
= Comparator.comparingInt(s -> ordering.indexOf(s) == -1 ? ordering.size() : ordering.indexOf(s));
Now your code prints:
Element "foo" is ordered before "baz".
In this form it is inefficient in that it calls indexOf() twice. If you’re concerned, I leave it to you to rewrite it to avoid that.
PS I changed comparing() to comparingInt().
is
Comparator.comparing()used for converting a single argument lambda expression to a double argument?
Yes, you can sort of think of it like that.
When sorting things, you are supposed to specify "given two things a and b, which of them is greater, or are they equal?" using a Comparator<T>. The a and b is why it has 2 lambda parameters, and you return an integer indicating your answer to that question.
However, a much more convenient way to do this is to specify "given a thing x, what part of x do you want to sort by?". And that is what you can do with the keyExtractor argument of Comparator.comparing.
Compare:
/*
given two people, a and b, the comparison result between a and b is the
comparison result between a's name and b's name
*/
Comparator<Person> personNameComparator =
(a, b) -> a.getName().compareTo(b.getName());
/*
given a person x, compare their name
*/
Comparator<Person> personNameComparator =
Comparator.comparing(x -> x.getName()); // or Person::getName
The latter is clearly much more concise and intuitive. We tend to think about what things to sort by, rather than how exactly to compare two things, and the exact number to return depending on the comparison result.
As for the declaration for comparing:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
The <T, U extends Comparable<? super U>> part first declares two generic type parameters - T is what the comparator compares (Person in the above case), and U is the type that you are actually comparing (String in the above case), hence it extends Comparable.
keyExtractor is the parameter you pass in, such as x -> x.getName(), that should answer the question of "when given a T, what is a U that you want to compare by?".
If you are confused by the ? super and ? extends, read What is PECS?.
If you haven't realised already, the implementation of comparing basically boils down to:
return (a, b) -> keyExtractor.apply(a).compareTo(keyExtractor.apply(b));
Comparator#compare(T o1, T o2) Compare two objects and returns an integer value based on this criteria:
- A negative value if o1 < o2
- A positive value if o1 > o2
- Zero if they are equal.
Comparator.comparing(Function<? super T, ? extends U> key) returns a Comparator<T> that compares by that sort key.
The main difference is that compare method provides a single point of comparison, whereas comparing chained to other functions to provide multiple points of comparison.
Suppose you have a class Person
public class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private int age;
// rest of class omitted
}
if you compare two Person instances p1 vs p2 using compare(p1, p2), the comparison will be executed and the two objects will be sorted based on some natural ordering prescribed by the class. In contrast, if you want to compare the same two instances using comparing(), the comparison will be executed based on whichever criteria you choose to compare based on some attribute of the class. For example: Comparator.comparing(Person::getFirstName).
Because comparing returns a Comparator rather than a value, as I stated before, you can chain multiple comparisons. For instance: Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName);
As for the meaning of the return type <T, U extends Comparable<? super U>> Comparator<T>, you can find the explanation here.
I want to add that, classes must be comparable in order for compare(T o1, T o2) to work. String objects are comparable because they implement this interface. That said, if a class is not Comparable, you can still use comparing method because as I stated, you get to choose which attribute of the class you would like to use for the comparison and those attributes are likely to be comparable (i.e. String in the case of person's name or age in the above example).
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.