Count the number of occurrences of each item in a list

I have streaming input that has duplicate values. I can use any data structure, but I have to count the number of events of each element. Suppose I have a list of mobile phone providers, such as:

Apple
Nokia
Samsung
Apple
LG
Nokia
HTC
Android
Apple
Nokia
Nokia
Apple
Samsung

I need to build any data structure, preferably a map with such details as

Apple 4
Nokia 4
Samsung 2
Lg 1
Android 1

I'm not sure how optimal this is. Is there a better solution than this?
Actually I still need to write above as code. Therefore, the best code will also help.

+5
source share
6

, Map<String, Integer>. add :

private static void incrementValue(Map<String, Integer> counters, String toAdd) {
    Integer currValue = counters.get(toAdd);
    if (currValue == null)
        counters.put(toAdd, 1);
    else
        counters.put(toAdd, currValue+1);
}

:

private static void incrementValue(Map counters, String toAdd) {
    Integer currValue = (Integer) counters.get(toAdd);
    if (currValue == null)
        counters.put(toAdd, 1);
    else
        counters.put(toAdd, currValue+1);
}
+5

, , Java 1.4, Apache Commons Collections, .

pjp , .

, Apache Commons Bag, getCount, , Bag.

add Integer HashBag , Integer Bag:

Bag b = new HashBag();

b.add(Integer.valueOf(1));
b.add(Integer.valueOf(2));
b.add(Integer.valueOf(2));
b.add(Integer.valueOf(3));

System.out.println("Count for 1: " + b.getCount(Integer.valueOf(1)));
System.out.println("Count for 2: " + b.getCount(Integer.valueOf(2)));
System.out.println("Count for 3: " + b.getCount(Integer.valueOf(3)));

:

Count for 1: 1
Count for 2: 2
Count for 3: 1

( , Java 6, , , -Java 5 .)

+4

? db - .

+1

, . :)

: value: .

0

, , , , - "code-value" . .

0

Bag aka Multiset.

A bag is essentially a function from object to graph.

Google collections have Multiset, however you can easily create your own using HashMap.

http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multiset.html

0
source

All Articles