Google News
logo
Java Program to Count the Frequency of each Element in Array
In the following example of Java program to count the frequency of each element in an array :
Program :
public class FrequencyCount {
    public static void main(String[] args) {
        int[] arr = {2, 3, 5, 2, 7, 3, 2, 5, 9, 9, 7, 3};
        int[] freq = new int[arr.length];
        int visited = -1;
        
        for(int i=0; i<arr.length; i++){
            int count = 1;
            for(int j=i+1; j<arr.length; j++){
                if(arr[i] == arr[j]){
                    count++;
                    freq[j] = visited;
                }
            }
            if(freq[i] != visited){
                freq[i] = count;
            }
        }
        
        System.out.println("Element\tFrequency");
        for(int i=0; i<freq.length; i++){
            if(freq[i] != visited){
                System.out.println(arr[i] + "\t" + freq[i]);
            }
        }
    }
}
Output :
Element	Frequency
2	3
3	3
5	2
7	2
9	2
In this program, we have an integer array arr. We create another integer array freq with the same length as arr. We initialize a variable visited with -1, which is used to mark the elements that have already been counted.

We loop through the array arr and for each element, we compare it with the rest of the elements. If we find a match, we increment a variable count. We also mark the index of the matching element in the freq array with visited.

After counting the frequency of all the elements, we loop through the freq array and print the non-visited elements along with their frequency.