2012-10-15 56 views

回答

4

通過每個迭代剛剛和維護

Map<Integer, Integer> numberToFrequencyMap; 
2

看看Apache CommonsCollectionUtils#getCardinalityMap

它返回一個Map<Element, Integer>在你的列表中的每個元素的頻率。

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

而且,你有一個CollectionUtils#cardinality,如果你想獲取數爲特定的元素。

+0

你爲什麼要在這裏演員? –

+0

@LouisWasserman是的,沒有必要。我很困惑它是否返回'Map <?擴展Object,整數>'.. –

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 

(披露:我對番石榴貢獻)

+0

+1。休息是所有孩子的戲劇;) –

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()); 
    }