0

可能重复:
如何计算列表中元素的出现次数

我有一个类似的列表List<String> A={12, 12, 14, 16, 16}。我怎样才能清楚地找到元素的数量

12->2
14->1
16->2

通过使用类似countElements(A,"12")or的函数A.count("12")?有库还是函数?

4

5 回答 5

4

只需遍历每个并维护一个

Map<Integer, Integer> numberToFrequencyMap;
于 2012-10-15T21:13:13.083 回答
4

Collections.frequency如果您只需要个别元素的频率,您也可以使用该方法。

于 2012-10-15T21:20:25.153 回答
2

看一眼Apache Commons CollectionUtils#getCardinalityMap

它返回Map<Element, Integer>列表中每个元素的频率。

List<String> list = {"12", "12", "14", "16", "16"};
Map<String, Integer> frequencyMapping = CollectionUtils.getCardinalityMap(list);

此外,CollectionUtils#cardinality如果要获取特定元素的计数,您还有一个。

于 2012-10-15T21:15:51.707 回答
1

如果您可以使用第三方依赖项,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

(披露:我为 Guava 做出了贡献。)

于 2012-10-15T21:20:46.110 回答
0

迭代你的数字,保持计数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());
   }
于 2012-10-15T21:36:21.130 回答