0

Possible Duplicate:
How to count occurrence of an element in a List
Count occurences of word in ArrayList

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?

Community
  • 1
  • 1
user1514499
  • 762
  • 7
  • 26
  • 63

2 Answers2

2

You have multiple options, you could use an Map<Item, Integer> and use the mapped value to store the frequency, this will be good for time complexity but not for space complexity.

for (Item i : list)
{
  Integer f = map.get(i);

  if (f == null)
    map.put(i, 1);
  else
    map.put(i, ++f);
}

Otherwise you could use some facility method like Collections.frequency(Collection<?> c, Object o) but this would be good only if you are looking for the frequency of a single element, otherwise you would need a set to check just the uniques so the first approach would be better.

Jack
  • 131,802
  • 30
  • 241
  • 343
2

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<Item> items = HashMultiset.create(list);
System.out.println(items.count(someItem));
for (Multiset.Entry<Item> entry : items.entrySet()) {
    System.out.println(entry.getElement() + " - " + entry.getCount() + " times");
}
Frank Pavageau
  • 11,477
  • 1
  • 43
  • 53