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;
    }
4

2 回答 2

7

等效的方法参考是comparing(Person::getStartDate)- 请注意,在您的特定情况下,您可以直接对流进行排序。此外,没有必要将您的方法限制为仅接受LinkedHashSets - 任何集合都可以:

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

注意所需的静态导入:

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
于 2015-06-15T17:38:35.257 回答
4

使用Comparator.comparing辅助方法:

Collections.sort(pList, Comparator.comparing(Person::getStartDate));
于 2015-06-15T17:25:49.253 回答