0

I have the list of following objects. Using Stream API, can I get a User with the number of frequency it appeared in the List?

public class User {
    string name;
    int age;
}
Eran
  • 374,785
  • 51
  • 663
  • 734
pannu
  • 478
  • 6
  • 20

1 Answers1

7

You can use groupingBy combined with counting:

Map<String,Long> countByName =    
    users.stream()
         .collect(Collectors.groupingBy(User::getName,Collectors.counting()));

This gives you the the count for each User name.

Eran
  • 374,785
  • 51
  • 663
  • 734