如何从列表中获取重复的值(count) [英] How to get the number of repeated values(count) from list
本文介绍了如何从列表中获取重复的值(count)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个列表以下值
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
我试图通过使用map来实现。这是正确的方法还是有更好的方法?
I am trying to implement this by using map. Is this the correct way or is there any better way?
推荐答案
您可以使用 Multiset $来自 Guava 的c $ c>
,这将计算出现次数的每个值。最简单的实现将是 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.
使用起来很简单:
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屋!
查看全文