Java 8 Streams: collector returning filtered object

Tumelo Galenos :

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.

Naman :

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)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147822&siteId=1