0

重複の可能性:
リスト内の要素の出現をカウントする方法

のようなリストがありList<String> A={12, 12, 14, 16, 16}ます。要素の数を明確に見つけるにはどうすればよいですか

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

countElements(A,"12")または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 に答える