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
  • 387,369
  • 54
  • 702
  • 768
pannu
  • 518
  • 7
  • 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
  • 387,369
  • 54
  • 702
  • 768