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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to count the number of occurance of specific element in array/list without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about How to count the number of occurance of specific element in array/list - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji