Accepts a function that extracts a sort key from a type T, and returns a Comparator<T> that compares by that sort key using the specified Comparator.
The returned comparator is serializable if the specified function and comparator are both serializable.
Biniman Idugboe wrote:1. At what point does the integer value returned by the Lambda expression become a Compartor?
2. Does an integer value become a Comparator just by prepending (Comparator<T> & Serializable) to it?
3. Inside the body of the comparing() method, which line of code produces the Comparator?
Let's forget about lines 5‑6 which simply prevent nulls being passed.Now, we have a common or garden λ, which I shall turn into an anonymous class. What precedes the -> is the parameters for a method and what follows it is the body of the method, and we know the method signature from hereNow, let's apply a name to the class.Now, we don't know what keyExtractor and keyComparator are. Maybe you have a Person class with String lastName. Maybe keyExtractor simply gets the lastName field. Maybe then keyComparator is a Comparator<String> which can compare Strings. You now have something similar to this λ:-As you know, Strings already implement Comparable<String>, so you can call compareTo on them.
Note: It is generally a good idea for comparators to also implement java.io.Serializable . . .
.flatMap(i -> Integer.toUnsignedString(i))
Reason: argument mismatch; bad return type in lambda expression
String cannot be converted to IntStream
.flatMap(i -> Integer.toString(i))
error: incompatible types: cannot infer type-variable(s) R
.flatMap(i -> toString(i))
error: method toString in class Object cannot be applied to given types;
.forEach(i -> i.toString())
error: int cannot be dereferenced