0

Possible Duplicate:
How to count occurrence of an element in a List

I have a list like List<String> A={12, 12, 14, 16, 16}. How can I find the number of elements distinctly as

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

by using a function like countElements(A,"12") or A.count("12")? Is there a library or a function?

Community
  • 1
  • 1
Saliha Uzel
  • 141
  • 2
  • 5
  • 17
  • 3
    You can find this: http://stackoverflow.com/questions/505928/how-to-count-occurrence-of-an-element-in-a-list very useful. – songokuhd Oct 15 '12 at 21:21

5 Answers5

4

Just iterate through each and maintain a

Map<Integer, Integer> numberToFrequencyMap;
jmj
  • 237,923
  • 42
  • 401
  • 438
4

You can also utililize the method Collections.frequency if you need the frequency of only some of the elements individually.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
2

Take a look at Apache Commons CollectionUtils#getCardinalityMap

It returns a Map<Element, Integer> with frequency of each element in your list.

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

Also, you have a CollectionUtils#cardinality if you want to fetch count for a specific element.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

If you can use third-party dependencies, Guava has a collection type for this called 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

(Disclosure: I contribute to Guava.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

Iterate your numbers, maintain the count in a Map as below:

    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());
   }
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73