Write a program to count the occurrences of an element in an array is one of the basic question which will be asked in a Java Interview. After the introduction of Collection framework performing this operation is a pretty easy task. Let see how we can count the occurrence using HashMap.
Java Program to count the occurrences of an element in an array
package com.javainterviewpoint; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class CountOccurence { public static void main(String[] args) { //Input Array int[] input = new int[]{ 1,4,5,2,3,5,1,6,4,7,1,3,6,8,2,5}; //countMap holds the count details of each element Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(); for (int i = 0; i < input.length; i++) { int key = input[i]; if (countMap.containsKey(key)) { int count = countMap.get(key); count++; countMap.put(key, count); } else { countMap.put(key, 1); } } //Printing the Element and its occurrence in the array for(Entry<Integer,Integer> val : countMap.entrySet()) { System.out.println(val.getKey() + " occurs " + val.getValue() + " time(s)"); } } }
Output :
Count the occurrences of an element in an array in Java
We will be performing the below steps to count the occurrence.
- As a first step we will be creating a HashMap “countMap” to hold the element (Key) and the count as the value.
- For each of the element in the input array, check if it is present in the countMap, using containsKey() method.
if (countMap.containsKey(key))
- If the element is present in the countMap, then increment the count flag by 1 and put the element as the Key and the count as the value to our countMap
count++; countMap.put(key, count);
- If the element is not present then add the element as the key and 1 as the value
countMap.put(key, 1);
- Finally print the countMap, which will be containing the elements and its occurrences.
Leave a Reply