1. List sorting
1. The java8 API has provided an available sort method for List; void sort(Comparator< ?
super E> c)
;
Let's deal with it:
because Comparator is a functional interface (a functional interface refers to only one abstract method in an interface class, allowing multiple default methods), you can use lambda expressions.
The function descriptor of Comparator is (T,T) -> int, which receives two T objects and returns an int. The effect of using lambda expression is as follows.
Since the java compiler can infer the parameter type of the lambda expression according to the context in which the lambda appears, and because the list generic type has been specified as the Apple type, the method parameter type can be omitted. Rewrite as follows:
Since Comparator provides a static auxiliary method of comparing, the source code is as follows: The
formal parameter is a Function function interface (receives a T type and returns a U type), and comparing is a comparison function that has been implemented and returns a Comparator The method of the object, so we can write it as follows:
Note that a static class is introduced above. Inferred from the context, it can be abbreviated as follows:
and lambda expression has another method reference (::) instead, because it can continue to be abbreviated: the
function interface provided by jdk1.8 provides related composite methods, and the operation can be Combined together, for example: Predicate interface provides negate(), and(), or() and other methods, redApple.and(a -> a.getWeight() > 50).or(a -> "green". equals(a. getColor()));
Basic usage of lambda expressions and method references in jdk1.8
Guess you like
Origin blog.csdn.net/u013326684/article/details/101172676
Ranking