StillLearningToCode
StillLearningToCode

Reputation: 2461

Find max size of an element among list of objects

@Data
class Person {

    private String fname;
    private String lname;

    private List<String> friends;
    private List<BigDecimal> ratings;

    ...
}

@Data
class People {

    private List<Person> people;

    ...
}

suppose i have the above classes, and need to figure out what is the most number of friends any one person has. I know the pre-streams way of doing it... by looping over every element in the list and checking if friends.size() is greater than the currently stored number of longest list. is there a way to streamline the code with streams? something like this answer?

Upvotes: 0

Views: 292

Answers (3)

GolamMazid Sajib
GolamMazid Sajib

Reputation: 9447

Your question already answered. but i add this for one thing. if your list of person size large and if you have multi-core pc and you want to used this efficiently then use parallelstream().

To get person:

Person person = people.getPeople()
.parallelStream()
.max(Comparator.comparingInt(p-> p.getFriends().size()))
.orElse(null);

To get size:

int size = people.getPeople()
.parallelStream()
.mapToInt(p -> p.getFriends().size())
.max().orElse(0);

Upvotes: 1

NiVeR
NiVeR

Reputation: 9796

You can declare the following method in Person class:

public int getNumberOfFriends(){
   return friends.size();
}

and then use it in a stream like this:

Optional <Person> personWithMostFriends = people.stream().max(Comparator.comparingInt(Person::getNumberOfFriends));

With this approach you will get the Person object with the most friends, not only the maximum number of friends as someone suggested.

Upvotes: 1

davidxxx
davidxxx

Reputation: 131436

Compute the max Person contained in People according to a comparator that relies on the size of Person.getFriends() :

Optional<Person> p = people.getPeople()
                           .stream()
                           .max(Comparator.comparingInt(p -> p.getFriends()
                                                           .size()));

Note that you could also retrieve only the max of friends without the Person associated to :

OptionalInt maxFriends = people.getPeople()
                               .stream()
                               .mapToInt(p -> p.getFriends()
                                               .size())
                               .max();

Upvotes: 7

Related Questions