Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Lambdas with method reference.

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;
    }
like image 684
amal Avatar asked Apr 27 '26 07:04

amal


2 Answers

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;
like image 139
assylias Avatar answered Apr 28 '26 19:04

assylias


Use Comparator.comparing helper method:

Collections.sort(pList, Comparator.comparing(Person::getStartDate));
like image 22
Tagir Valeev Avatar answered Apr 28 '26 20:04

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!