3

how can we write the Lambda expression statement

Collections.sort(list,(a1,a2) -> (a1.getName().compareTo(a2.getName())));

into method references?

2 Answers 2

6
Collections.sort(list, Comparator.comparing(Item::getName));

Or better yet,

list.sort(Comparator.comparing(Item::getName));
Sign up to request clarification or add additional context in comments.

Comments

0

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> 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.