0

I have a list of five numbers (a hand of cards). I'd like to get the frequency of each number in the list, and put that in a map, or something similar.

I know it's easy to implement this yourself. But I was curious, is there a way to do so in the Collections framework?


(To be clear, not the frequency of any particular number, but the frequency of every number, in the list.)

ktm5124
  • 11,861
  • 21
  • 74
  • 119

3 Answers3

1

There is a method in the (Collections)[http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html] class called frequency

It is used as follows:

int occurrences = Collections.cards(animals, "1");

I'm pretty sure this is JDK 1.6 updwards

Jamie Reid
  • 532
  • 2
  • 17
  • Yeah, I know about the frequency method. But it's not what I want. Because you have to give a specified element. I'd like it to return me a map of frequencies for all values. – ktm5124 Feb 28 '15 at 18:22
  • In which case, no real method that I am aware of other than looping through the list and adding to a map and increasing one by one. – Jamie Reid Feb 28 '15 at 18:24
1

Use a Guava HashMultiset, it has the counting built right into it:

HashMultiset<String> set = HashMultiset.create(yourList);
int x = set.count("abc");

You can also iterate and get the count over all elements:

for(Multiset.Entry<String> entry : set.entrySet()) { 
    System.out.println(entry.getElement() + " -> " + entry.getCount());
}
Thomas Jungblut
  • 20,854
  • 6
  • 68
  • 91
0

Try this

List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(1);
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(4);
    list.add(1);
    Set<Integer> set = new HashSet<Integer>(list);
    for(Integer tmp:set)
    {       
    System.out.println("frequency of element "+ tmp + " : " + Collections.frequency(list, tmp));
    }
underdog
  • 4,447
  • 9
  • 44
  • 89