2

Please help me to understand how to replace lambdas with method reference for the method below.

 public List<Person> sortByStartDate_ASC(LinkedHashSet<Person> personList) {
 List<Person> pList = new ArrayList<Person>(personList);
 Collections.sort(pList, (Person person1, Person person2) -> person1
 .getStartDate().compareTo(person2.getStartDate()));
 return pList;
 }
assylias
330k84 gold badges680 silver badges806 bronze badges
asked Jun 15, 2015 at 16:55

2 Answers 2

7

The equivalent method reference would be comparing(Person::getStartDate) - note that in your specific case you could sort the stream directly. Also there is no point restricting your method to only accept LinkedHashSets - any collection would do:

public List<Person> sortByStartDate_ASC(Collection<Person> personList) {
 return personList.stream()
 .sorted(comparing(Person::getStartDate))
 .collect(toList());
}

Note required static imports:

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
answered Jun 15, 2015 at 17:38
Sign up to request clarification or add additional context in comments.

Comments

4

Use Comparator.comparing helper method:

Collections.sort(pList, Comparator.comparing(Person::getStartDate));
answered Jun 15, 2015 at 17:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.