How to Count Element Frequency of a Collection in Java


In this example, we can get the method to get how many times an element occurs in a collection.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class FrequencyExample {
 
    public static void main(String a[]){
         
        List list = new ArrayList();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("2");
        list.add("4");
        list.add("3");
        list.add("5");
        list.add("6");
        // get frequency
        System.out.println("Frequency of element '1' is : " + Collections.frequency(list, "1"));
        System.out.println("Frequency of element '2' is : " + Collections.frequency(list, "2"));
        System.out.println("Frequency of element '3' is : " + Collections.frequency(list, "3"));
    }
}

Output:

Frequency of element '1' is : 1
Frequency of element '2' is : 2
Frequency of element '3' is : 2

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments