How to get the number of repeated values(count) from list [duplicate]

微笑、不失礼 提交于 2019-12-25 03:25:08

问题


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?


回答1:


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");
}



回答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.



来源:https://stackoverflow.com/questions/11642151/how-to-get-the-number-of-repeated-valuescount-from-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!