Organizational Research By

Surprising Reserch Topic

How to get the number of repeated values(count) from list in java

Assume I have a List the following values

emp1, emp2, emp3, emp2, emp1, emp4, emp1

I need to get the number of times a string is repeated such as the following

emp1 - 3 times  
emp2 - 2 times  
emp3 - 1 times  
emp4 - 1 times  

I am trying to implement this by using map. Is this the correct way or is there any better way?


asked Jun 22, 2015 in Core java by rahulgii
0 votes

Related Hot Questions

1 Answer

0 votes
You can use a Multiset from Guava, which will count the number of occurrences of each value. The simplest implementation would be HashMultiset, but you can also use a immutable implementation such as ImmutableMultiset if you need to keep it around.

It's as simple to use as:

Multiset items = HashMultiset.create(list);
for (Multiset.Entry entry : items.entrySet()) {
    System.out.println(entry.getElement() + " - " + entry.getCount() + " times");
answered Jun 22, 2015 by rahulgii