【问题标题】:Java: count of elements in a list [duplicate]Java:列表中的元素计数[重复]
【发布时间】:2012-10-05 22:13:56
【问题描述】:

可能重复:
How to count occurrence of an element in a List

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

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

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

【问题讨论】:

标签: java list


【解决方案1】:

只需遍历每个并维护一个

Map<Integer, Integer> numberToFrequencyMap;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      看看Apache CommonsCollectionUtils#getCardinalityMap

      它返回一个Map&lt;Element, Integer&gt;,其中包含列表中每个元素的频率。

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

      此外,如果您想获取特定元素的计数,您可以使用 CollectionUtils#cardinality

      【讨论】:

      • 你为什么要在这里投?
      • @LouisWasserman 是的,没必要。我很困惑它是否返回Map&lt;? extends Object, Integer&gt;..
      【解决方案4】:

      如果您可以使用第三方依赖项,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 做出了贡献。)

      【讨论】:

      • +1 表示贡献。休息对你来说都是孩子的游戏;)
      【解决方案5】:

      迭代您的数字,将计数保持在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());
         }
      

      【讨论】:

        猜你喜欢
        • 2014-04-19
        • 2023-03-11
        • 2011-05-07
        • 2017-11-09
        • 2020-06-04
        • 1970-01-01
        • 2018-11-04
        • 2019-08-01
        • 2020-06-27
        相关资源
        最近更新 更多