How to count the number of occurance of specific element in array/list

I am new to java and develeping a small application in java, right now i stuck at a point. I have a custom class named Candidate. It looks like:

=============================
|Candidate Class            |
=============================
|Private Members:           |
|Node Array                 |
|IsValid Bool               |
-----------------------------
|Public Methods:            |
|AddCandidateNode           |
|SetIsValid                 |
|ComparisonOperatorOverloaded|
=============================

Now i have a an array containing list of all candidates and i want to know the frequency of occurrence of each candidate in that array. One way i have in my mind is to write two loops and make comparisons using the overloaded method. But i don’t want to use that. So i just want to conform that is there any built in method that did the same for me?

Answer

This is a classic problem. The solution is to use a map in which the keys are the items from your array and the values are the counts.

The code in psuedocode-close-to-Java looks like this:

Map<Candidate, Integer> map = new HashMap<Candidate, Integer>();
for (Candidate c: Candidates) {
    if (map.containsKey(c)) {
        map.put(c, map.get(c) + 1);
    } else {
        map.put(c, 1);
    }
}

After you run this the counts will be in the map.

Leave a Reply

Your email address will not be published. Required fields are marked *