Java 8 Streams:收集器返回过滤后的对象

假设我有一个集合,我想过滤到每所学校最古老的集合。


到目前为止,我有:


Map<String, Long> getOldestPerSchool(Set<Person> persons) {

  return persons.stream().collect(Collectors.toMap(Person::getSchoolname, Person::getAge, Long::max);

}

麻烦的是,我想要的是整个人而不是名字。但是,如果我将其更改为:


Map<Person, Long> getOldestPerSchool(Set<Person> persons) {

  return persons.stream().collect(Collectors.toMap(p -> p, Person::getAge, Long::max);

}

我得到所有人,我不一定需要地图。


潇潇雨雨
浏览 506回答 2
2回答

萧十郎

设置我想过滤到每所学校最老的。假设最老的每所学校意味着最老Person的 perschool,您可能正在寻找如下输出:Map<String, Person> getOldestPersonPerSchool(Set<Person> persons) {&nbsp; &nbsp; return persons.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Person::getSchoolname,&nbsp; // school name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Function.identity(), // person&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (a, b) -> a.getAge() > b.getAge() ? a : b)); // ensure to store oldest (no tie breaker for same age)}

暮色呼如

您可以通过中间分组来实现这一点,然后只values()在生成的分组列表中流式传输,您只需选择最年长的人Set<Person> oldestPerSchool = persons.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Stream<Person>&nbsp; &nbsp; .collect(Collectors.groupingBy(Person::getSchoolname)) // Map<String, List<Person>>&nbsp; &nbsp; .values().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Stream<List<Person>>&nbsp; &nbsp; .map(list -> list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// (Inner) Stream<Person>&nbsp; &nbsp; &nbsp; &nbsp; .max(Comparator.comparingInt(Person::getAge))&nbsp; &nbsp; &nbsp; // (Inner) Optional<Person>&nbsp; &nbsp; &nbsp; &nbsp; .get()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// (Inner) Person&nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Stream<Person>&nbsp; &nbsp; .collect(Collectors.toSet());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Set<Person>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java