Levan Levan - 5 months ago 9
Java Question

Return String from Java stream

I have a class

Person
, which stores the code of each person and a list of friends. I'm trying to get the code of the person with the highest number of friends, but cannot figure it out. The methods
getFriends
and
getCode
are provided by the
Person
class.

How can I return a string from the stream?

HashMap<String,Person> persons = new HashMap<>();

public String personWithLargestNumberOfFriends() {
return persons.values().stream()
.sorted(comparing(p -> ((Person)p).getFriends().size()).reversed())
.limit(1)
.forEach(p -> ((Person)p).getCode());
}

Answer

Instead of sorting, use max().

return persons.values().stream()
    .max(comparing(Person::getFriends, comparingInt(List::size)))
    .map(Person::getCode)
    .orElse("empty code");

See the Optional class to see if some other getter would suit your needs, like orElseThrow().