Levan Levan - 1 year ago 82
Java Question

Return String from Java stream

I have a class

, 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
are provided by the

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())
.forEach(p -> ((Person)p).getCode());

Answer Source

Instead of sorting, use max().

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download