[英]How to write Lambda expression into method references?
how can we write the Lambda expression statement 我们如何编写Lambda表达式语句
Collections.sort(list,(a1,a2) -> (a1.getName().compareTo(a2.getName())));
into method references? 进入方法参考?
Collections.sort(list, Comparator.comparing(Item::getName));
或者更好,
list.sort(Comparator.comparing(Item::getName));
Remember, a lambda expression is basically the implementation of a single method defined by a functional interface. 请记住,lambda表达式基本上是由功能接口定义的单个方法的实现。
Any method that has a matching signature (except method name), can be used by reference in place of a lambda expression. 任何具有匹配签名(方法名称除外)的方法都可以通过引用来代替lambda表达式。
In your case, it's the Comparator<? super T>
在你的情况下,它是
Comparator<? super T>
Comparator<? super T>
interface and it's int compare(T o1, T o2)
method, so any method that returns an int
and takes two arguments of the type of the collection elements will do. Comparator<? super T>
interface和它的int compare(T o1, T o2)
方法,所以任何返回int
并且采用集合元素类型的两个参数的方法都可以。
So, if your list is a List<Person>
, any method like this will work, regardless of method name: 因此,如果您的列表是
List<Person>
,那么无论方法名称如何,任何类似的方法都将起作用:
public static int xxx(Person p1, Person p2) { ... }
The method can have any visibility (public, private, ...) and doesn't have to be static. 该方法可以具有任何可见性(公共,私有,......),并且不必是静态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.