ktm5124
ktm5124

Reputation: 12123

How to get the frequency of numbers in a list

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.)

Upvotes: 0

Views: 1367

Answers (3)

Thomas Jungblut
Thomas Jungblut

Reputation: 20969

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

Upvotes: 1

techPackets
techPackets

Reputation: 4506

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

Upvotes: 0

Jamie Reid
Jamie Reid

Reputation: 552

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

Upvotes: 1

Related Questions