Home >>Java Programs >Java Program to find the frequency of each element in a array
In this program, we will create a java program to count the occurrence of each element in the array.
In this program, we will maintain one array to store the counts of each element of the array. We will loop through the array and count the occurrence of each element as frequency and store it in another array fr.
Program:
public class Main
{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1, 5, 7, 3, 5, 9, 8};
int [] fr = 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++;
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}
System.out.println("---------------------------------------");
System.out.println(" Element | Frequency");
System.out.println("---------------------------------------");
for(int i = 0; i < fr.length; i++){
if(fr[i] != visited)
System.out.println(" " + arr[i] + " | " + fr[i]);
}
System.out.println("----------------------------------------");
}
}
--------------------------------------- Element | Frequency --------------------------------------- 1 | 2 2 | 4 8 | 2 3 | 2 5 | 3 7 | 1 9 | 1 ----------------------------------------