Posted on by Kalkicode
Code Hash

# Find the frequency of each element in an array in java

Java program for Find the frequency of each element in an array. Here problem description and other solutions.

``````/*
Java program
Count frequency of each element in array
*/
import java.util.HashMap;
public class Occurrence
{
// Function which is display array elements
public static void display(int[] arr)
{
for (int i = 0; i < arr.length; ++i)
{
System.out.print("   " + arr[i]);
}
System.out.print("\n");
}
// Count occurrence of given array
public static void frequency(int[] arr)
{
// Display given array
display(arr);
// Create a empty map
HashMap < Integer, Integer > map =
new HashMap < Integer, Integer > ();
for (int i = 0; i < arr.length; i++)
{
if (map.containsKey(arr[i]))
{
// When key exists then update value
map.put(arr[i], map.get(arr[i]) + 1);
}
else
{
// Add new element
map.put(arr[i], 1);
}
}
System.out.println("  Occurrence ");
//  Display calculated result
for (int key: map.keySet())
{
System.out.println("  " + key + "  :  " + map.get(key));
}
}
public static void main(String[] args)
{
// Array element
int[] arr = {
1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
};
frequency(arr);
}
}``````

Output

``````   1   3   2   1   4   2   7   9   1   3   3   4   7
Occurrence
1  :  3
2  :  2
3  :  3
4  :  2
7  :  2
9  :  1``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post