简体   繁体   中英

How to write Lambda expression into method references?

how can we write the Lambda expression statement

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.

Any method that has a matching signature (except method name), can be used by reference in place of a lambda expression.

In your case, it's the 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.

So, if your list is a List<Person> , any method like this will work, regardless of method name:

public static int xxx(Person p1, Person p2) { ... }

The method can have any visibility (public, private, ...) and doesn't have to be static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM