如何从列表中获取重复值(count)的数量 [英] How to get the number of repeated values(count) from list
问题描述
可能重复:
计数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?
推荐答案
您可以使用 Multiset
(来自 Guava ),它会计算发生的次数的每个值。最简单的实现方式是 HashMultiset
,但您也可以使用不可变的实现,例如 ImmutableMultiset
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:
c $ c> 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 );
}
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");
}
这篇关于如何从列表中获取重复值(count)的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!