Basic usage of lambda expressions and method references in jdk1.8

1. List sorting
1. The java8 API has provided an available sort method for List; void sort(Comparator< ?
super E> c)
;
insert image description here
insert image description here
Let's deal with it:
insert image description here
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.
insert image description here
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:
insert image description here
Since Comparator provides a static auxiliary method of comparing, the source code is as follows: The
insert image description here
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:
insert image description here
Note that a static class is introduced above. Inferred from the context, it can be abbreviated as follows:
insert image description here
and lambda expression has another method reference (::) instead, because it can continue to be abbreviated: the
insert image description here
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()));

Guess you like

Origin blog.csdn.net/u013326684/article/details/101172676