简体   繁体   中英

Java 8 Streams: collector returning filtered object

Say I have a Set that I'd like to filter down to the oldest per school.

So far I have:

Map<String, Long> getOldestPerSchool(Set<Person> persons) {
  return persons.stream().collect(Collectors.toMap(Person::getSchoolname, Person::getAge, Long::max);
}

Trouble is, I want the whole person instead of only the name. But if I change it to:

Map<Person, Long> getOldestPerSchool(Set<Person> persons) {
  return persons.stream().collect(Collectors.toMap(p -> p, Person::getAge, Long::max);
}

I get all persons, and I do not necessarily need a Map.

Set that I'd like to filter down to the oldest per school.

Assuming oldest per school meant oldest Person per school , you are possibly looking for an output like:

Map<String, Person> getOldestPersonPerSchool(Set<Person> persons) {
    return persons.stream()
            .collect(Collectors.toMap(
                    Person::getSchoolname,  // school name
                    Function.identity(), // person
                    (a, b) -> a.getAge() > b.getAge() ? a : b)); // ensure to store oldest (no tie breaker for same age)
}

You can achieve this with an intermediate grouping and then only streaming over the values() of the resulting grouped list, there you just select the oldest person

Set<Person> oldestPerSchool = persons.stream()             // Stream<Person>
    .collect(Collectors.groupingBy(Person::getSchoolname)) // Map<String, List<Person>>
    .values().stream()                                     // Stream<List<Person>>
    .map(list -> list.stream()                             // (Inner) Stream<Person>
        .max(Comparator.comparingInt(Person::getAge))      // (Inner) Optional<Person>
        .get()                                             // (Inner) Person
    )                                                      // Stream<Person>
    .collect(Collectors.toSet());                          // Set<Person>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM