Java:列表中元素的数量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12904084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: count of elements in a list
提问by Saliha Uzel
Possible Duplicate:
How to count occurrence of an element in a List
可能的重复:
如何计算列表中元素的出现次数
I have a list like List<String> A={12, 12, 14, 16, 16}
. How can I find the number of elements distinctly as
我有一个像List<String> A={12, 12, 14, 16, 16}
. 我怎样才能清楚地找到元素的数量
12->2
14->1
16->2
by using a function like countElements(A,"12")
or A.count("12")
? Is there a library or a function?
通过使用像countElements(A,"12")
或这样的函数A.count("12")
?有库或函数吗?
回答by Jigar Joshi
Just iterate through each and maintain a
只需遍历每个并维护一个
Map<Integer, Integer> numberToFrequencyMap;
回答by Bhesh Gurung
You can also utililize the method Collections.frequency
if you need the frequency of only some of the elements individually.
Collections.frequency
如果您只需要个别元素的频率,您也可以使用该方法。
回答by Rohit Jain
Take a look at Apache Commons
CollectionUtils#getCardinalityMap
看一眼 Apache Commons
CollectionUtils#getCardinalityMap
It returns a Map<Element, Integer>
with frequency of each element in your list.
它返回Map<Element, Integer>
列表中每个元素的频率。
List<String> list = {"12", "12", "14", "16", "16"};
Map<String, Integer> frequencyMapping = CollectionUtils.getCardinalityMap(list);
Also, you have a CollectionUtils#cardinality
if you want to fetch count for a specific element.
此外,CollectionUtils#cardinality
如果您想获取特定元素的计数,您还有一个。
回答by Louis Wasserman
If you can use third-party dependencies, Guavahas a collection type for this called Multiset
:
如果您可以使用第三方依赖项,Guava有一个名为 的集合类型Multiset
:
Multiset<String> multiset = HashMultiset.create(list);
multiset.count("foo"); // number of occurrences of foo
multiset.elementSet(); // returns the distinct strings in the multiset as a Set
multiset.entrySet(); // returns a Set<Multiset.Entry<String>> that you can
// iterate over to get the strings and their counts at the same time
(Disclosure: I contribute to Guava.)
(披露:我为番石榴做出了贡献。)
回答by Yogendra Singh
Iterate your numbers, maintain the count in a Map
as below:
迭代您的数字,将计数保持在 a 中Map
,如下所示:
List<Integer> myNumbers= Arrays.asList(12, 12, 14, 16, 16);
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
for(int i=0; i<myNumbers.size(); i++){
Integer myNum = myNumbers.get(i);
if(countMap.get(myNum)!= null){
Integer currentCount = countMap.get(myNum);
currentCount = currentCount.intValue()+1;
countMap.put(myNum,currentCount);
}else{
countMap.put(myNum,1);
}
}
Set<Integer> keys = countMap.keySet();
for(Integer num: keys){
System.out.println("Number "+num.intValue()+" count "+countMap.get(num).intValue());
}