To count the number of occurence of each elements in java, using HashMap is the most efficient and standard approach, which runs on O(n) time complexity.
Example :
import java.util.HashMap;
import java.util.Arrays;
public class ElementCounter{
//Method to count the occurence of each elements in array
public static void arrayElementCount(int array[] ) {
// Creating a HashMap object with elements of input array as keys and their count ie. occurence of each elements count as values .
HashMap<Integer,Integer> elementCountMap= new HashMap<Integer, Integer>();
//Checking every element of the input array
for(int i: array) {
if(elementCountMap.containsKey(i)){
//If the element is present in the elementCountMap , increment it’s count by 1 .
elementCountMap.put( i , elementCountMap.get(i)+1);
}
else{
// If the element is not present in the elementCountMap , then add this element to the elementCountMap with 1 as it’s count value.
elementCountMap.put( i , 1 ) ;
}
}
System.out.println(“Input Array is:”+Arrays.toString(array));
System.out.println(“Occurence of each element in the array”+elementCountMap);
}
public static void main (String args[] ) {
int array[ ]=new int[ ] {3,5,6,7,3,5,9,6};
arrayElementCount(array);
}
}
OUTPUT:
Input Array is : [ 3 , 5 , 6 , 7, 3, 5, 9, 6 ]
Occurence of each element in the array { 3=2 , 5=2 , 6=2 , 7=1 , 9=1 }
