Search code examples
javadata-structurescollections

Counting the number of occurrences of each item in a list


I have a streaming input which has repeated values. I can use any data structure but I have to count the number of occurence of each element. Suppose I have a list of mobile phone suppliers like the following:

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

I have to build any data structure preferably a map with details like

Apple,4
Nokia,4
Samsung,2
LG,1
Android,1

I am not sure whether this is optimal. Is there a better solution than this?
In fact I have yet to write the above as a code. So better code will also help.


Solution

  • Yes, I would use a Map<String, Integer>. I would wrap the add in something like this:

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

    Or without generics:

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