In this tutorial, we will write a java program to find the frequency of each element in the array.
For example, if an array is {2, 2, 3, 4, 3, 4, 2} then the frequency of element “2” is 3, frequency of element “3” is 2 and frequency of element “4” is 2.
Java Program to find the frequency of each element in the array
In the following example, we have an array numbers. In this array there are elements that reappeared again and we need to count the frequency of each element.
We ran a nested for loop(loop inside loop), in such a way that the each element of an array is compared to the all the elements of the same array, and every time there is a match, we increase the value of the count variable that counts the frequency.
Since, elements appeared multiple times, we need to avoid counting the frequency of same element again. For this, we have assigned a -1 value to the already counted elements using counted variable.
In the end, elements and their frequency in the array is displayed, here also we are using the counted variable to avoid printing the frequency of same element again.
public class JavaExample {
public static void main(String[] args) {
//Initializing an array
int [] numbers = new int [] {2, 2, 3, 4, 5, 5, 5, 3, 2, 4};
//This array will store the frequency of each element
int [] frequency = new int [numbers.length];
int counted = -1;
for(int i = 0; i < numbers.length; i++){
int count = 1;
for(int j = i+1; j < numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
//To avoid counting the frequency of same element again
frequency[j] = counted;
}
}
if(frequency[i] != counted)
frequency[i] = count;
}
//Printing the frequency of each element
for(int i = 0; i < frequency.length; i++){
if(frequency[i] != counted)
System.out.println("Element: "+numbers[i] + " Frequency: " + frequency[i]);
}
}}
Output:
Element: 2 Frequency: 3 Element: 3 Frequency: 2 Element: 4 Frequency: 2 Element: 5 Frequency: 3
Leave a Reply