重複の可能性:
リスト内の要素の出現をカウントする方法
のようなリストがありList<String> A={12, 12, 14, 16, 16}
ます。要素の数を明確に見つけるにはどうすればよいですか
12->2
14->1
16->2
countElements(A,"12")
またはA.count("12")
?のような関数を使用して ライブラリまたは関数はありますか?
重複の可能性:
リスト内の要素の出現をカウントする方法
のようなリストがありList<String> A={12, 12, 14, 16, 16}
ます。要素の数を明確に見つけるにはどうすればよいですか
12->2
14->1
16->2
countElements(A,"12")
またはA.count("12")
?のような関数を使用して ライブラリまたは関数はありますか?
それぞれを繰り返して維持するだけです
Map<Integer, Integer> numberToFrequencyMap;
Collections.frequency
一部の要素のみの頻度が個別に必要な場合にも、この方法を利用できます。
を見てみましょうApache Commons
CollectionUtils#getCardinalityMap
Map<Element, Integer>
リスト内の各要素の頻度を返します。
List<String> list = {"12", "12", "14", "16", "16"};
Map<String, Integer> frequencyMapping = CollectionUtils.getCardinalityMap(list);
また、CollectionUtils#cardinality
特定の要素のカウントを取得する場合もあります。
サードパーティの依存関係を使用できる場合、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に貢献しています。)
あなたの数を繰り返して、以下のように数を維持してください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());
}