开发者

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

开发者 https://www.devze.com 2023-03-22 11:31 出处:网络
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:

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开发者_如何学Python 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?


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.


There is an easier way if you are looking for the frequency of a specific element:

final String[] fruits = { "apple", "orange", "pear", "apple" };
final List<String> fruitList = Arrays.asList(fruits);
System.out.println(Collections.frequency(fruitList, "apple")); // Prints 2


I guess there is no such way other then looping through the ArrayList.

I will show you one simple way that I wrote for that scenario long time ago :)

Assuming that you have implemented the hashcode() and equals() functions for the Candidate class.

HashMap<Candidate,Integer> counter = new HashMap<Candidate,Integer>();

for( Candidate can : andidateArray ){
    if(counter.get(can) == null){
        counter.put(can,1);
    }else{
        counter.put( can, counter.get(can) + 1 );
    }
}


You can use guava's MultiSet:

Multiset<String> counter = HashMultiset.create(Arrays.asList("apple","apple","orange"));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号