1

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());
}
1
  • Regardless of what you want to do with a Stream, as soon as you forget about the existence of forEach, solutions will arise… Commented Jun 27, 2016 at 11:57

1 Answer 1

6

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.