Java Reference
In-Depth Information
inventory.sort(new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
});
3.7.3. Step 3: Use lambda expressions
But your current solution is still verbose. Java 8 introduces lambda expressions, which provide a
lightweight syntax to achieve the same goal: passing code . You saw that a lambda expression
can be used where a functional interface is expected. As a reminder, a functional interface is an
interface defining only one abstract method. The signature of the abstract method (called
function descriptor ) can describe the signature of a lambda expression. In this case, the
Comparator represents a function descriptor (T, T) -> int. Because you're using apples, it
represents more specifically (Apple, Apple) -> int. Your new improved solution looks therefore
as follows:
inventory.sort((Apple a1, Apple a2)
-> a1.getWeight().compareTo(a2.getWeight())
);
We explained that the Java compiler could infer the types of the parameters of a lambda
expression by using the context in which the lambda appears. So you can rewrite your solution
like this:
inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));
Can you make your code even more readable? Comparator has a static helper method called
comparing that takes a Function extracting a Comparable key and produces a Comparator
object (we explain why interfaces can have static methods in chapter 9 ) . It can be used as follows
(note that you now pass a lambda with only one argument: the lambda specifies how to extract
the key to compare with from an apple):
Comparator<Apple> c = Comparator.comparing((Apple a) -> a.getWeight());
You can now rewrite your solution in a slightly more compact form:
import static java.util.Comparator.comparing;
inventory.sort(comparing((a) -> a.getWeight()));
 
Search WWH ::




Custom Search