Reputation: 41
Following is my requirement: I have to count the occurrence of a particular item in a List and then print the item along with its occurrence count. For this I have the following code:
public void countOccurrences(Collection<String> list){
Map<String, Integer> occurrenceMap = new HashMap<String, Integer>();
for(String obj: list){
Integer numOccurrence = occurrenceMap.get(obj);
if(numOccurrence == null){
//first count
occurrenceMap.put(obj, 1);
} else{
occurrenceMap.put(obj, numOccurrence++);
}
}
for (Map.Entry<String, Integer> entry : occurrenceMap.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
Now say for example items added to my list are as follows:
list.add("apple");
list.add("apple");
list.add("apple");
list.add("banana");
list.add("banana");
list.add("mango");
The output that I'm expecting is
apple:3
banana:2
mango:1
However, the output that is coming is
apple:1
banana:1
mango:1
What am I missing here?
Upvotes: 1
Views: 82
Reputation: 544
you can also use following piece of code to achieve your objective.
public static void countOccurrences(Collection<String> list){
Map<String, Integer> occurrenceMap = new HashMap<String, Integer>();
Integer temp;
for(String obj: list){
if((temp = occurrenceMap.put(obj, 1))!= null){
occurrenceMap.put(obj, ++temp);
}
}
for (Map.Entry<String, Integer> entry : occurrenceMap.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
Upvotes: 0
Reputation: 4418
You can try in this way :
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("apple");
list.add("apple");
list.add("banana");
list.add("banana");
list.add("mango");
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
System.out.println(key + ": " + Collections.frequency(list, key));
}
Output:
banana: 2
apple: 3
mango: 1
Upvotes: 0
Reputation: 122008
You need to change the logic in your else part
occurrenceMap.put(obj, ++numOccurrence);
Because the post increment
numOccurrence ++
Returns the value of numOccurrence
and then increments numOccurrence
's value by 1. Hence you are not putting the latest one in the map.
Upvotes: 2
Reputation: 992
I think you need to change
occurrenceMap.put(obj, numOccurrence++);
to
occurrenceMap.put(obj, numOccurrence + 1);
or occurrenceMap.put(obj, ++numOccurrence);
numOccurrence++
will increment numOccurrence
after the statement. And it will never be used as numOccurrence
is reasigned next time the loop goes around.
Upvotes: 1