Count Frequencies of Elements in an Array Using Hashing in Java

 

 

Java Program


import java.util.HashMap;
import java.util.Map;

public class FrequencyCounter {

    /**
     * Counts the frequency of each element in the given array.
     * 
     * @param array the array of integers for which frequencies are to be counted
     * @return a map containing elements and their corresponding frequencies
     */
    public static Map<Integer, Integer> countFrequencies(int[] array) {
        Map<Integer, Integer> frequencyMap = new HashMap<>();

        for (int number : array) {
            // If the number is already in the map, increment its count
            frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1);
        }
        
        return frequencyMap;
    }

    public static void main(String[] args) {
        // Sample array
        int[] array = {1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5};

        // Count frequencies
        Map<Integer, Integer> frequencies = countFrequencies(array);

        // Print the frequencies
        System.out.println("Frequencies of elements:");
        for (Map.Entry<Integer, Integer> entry : frequencies.entrySet()) {
            System.out.println("Element: " + entry.getKey() + ", Frequency: " + entry.getValue());
        }
    }
}

Program Structure

The program consists of a single class, FrequencyCounter, which contains:

  • countFrequencies method: This method takes an integer array as input and returns a map containing each unique element and its frequency in the array.
  • main method: This is the entry point of the program. It initializes a sample array, calls the countFrequencies method, and prints the frequencies of the elements.

Explanation of Key Components

  • HashMap: The HashMap is used for efficient storage and retrieval of frequencies. The keys are the unique elements of the array, and the values are their respective counts.
  • for-each loop: This loop iterates through each element in the array to count the frequencies.
  • getOrDefault method: This method is used to fetch the current count of an element or return 0 if it doesn’t exist in the map yet.

Output

When the program is run with the sample array, the output will be:


Frequencies of elements:
Element: 1, Frequency: 1
Element: 2, Frequency: 2
Element: 3, Frequency: 3
Element: 4, Frequency: 1
Element: 5, Frequency: 4

 

Leave a Reply

Your email address will not be published. Required fields are marked *