Core Java

Java Array: Count Distinct Elements Frequencies

In programming, one common task is counting the number of times a specific element appears in an array. This is a fundamental problem that can be solved in multiple ways depending on the language and data structure used. Let us delve into understanding how to count distinct elements and their frequencies in a Java array. This task is a common challenge when dealing with data processing or analysis, where knowing the unique elements and how often they occur is essential.

1. Count Occurrences

The most straightforward method to count occurrences of an element in an array is by iterating through the array and incrementing a counter each time the element is found. Here’s an example:

1.1 Code Example

public class CountOccurrences {
    public static void main(String[] args) {
        // Initialize an array with some integer values
        int[] array = {
                1,
                2,
                2,
                3,
                4,
                2,
                5,
                2
        };

        // Define the target number to count in the array
        int target = 2;

        // Initialize a counter to keep track of occurrences of the target number
        int count = 0;

        // Loop through each element in the array
        for (int i : array) {
            // If the current element matches the target number, increment the counter
            if (i == target) {
                count++;
            }
        }

        // Print the result to the console
        System.out.println("The number " + target + " occurs " + count + " times.");
    }
}

This code initializes an integer array and a target number whose occurrences we want to count. It then iterates through the array using a for-each loop. If the current element matches the target, the count is incremented. Finally, the total count is printed.

The code prints the following output on the IDE console.

The number 2 occurs 4 times.

2. Using a Counters Array

If you want to count the occurrences of multiple elements simultaneously, you can use an auxiliary array (counters array) where each index corresponds to an element value in the original array. This is particularly useful if the array elements are within a known range (e.g., 0 to 9).

2.1 Code Example

public class CountersArray {
    public static void main(String[] args) {
        // Initialize an array with some integer values
        int[] array = {
                1,
                2,
                2,
                3,
                4,
                2,
                5,
                2
        };

        // Initialize a counter array to keep track of occurrences of each number
        // Assuming the numbers are in the range 0-5
        int[] counter = new int[6];

        // Loop through each element in the array
        for (int i : array) {
            // Increment the counter for the current element
            counter[i]++;
        }

        // Loop through the counter array to print the occurrences of each number
        for (int i = 0; i < counter.length; i++) {
            // Print the result to the console
            System.out.println("Number " + i + " occurs " + counter[i] + " times.");
        }
    }
}

Here, we create an auxiliary array called counter, where the index represents each possible value in the original array. As we iterate through the array, we increment the corresponding index in the counter array. Finally, we print out how many times each number appears in the original array.

The code prints the following output on the IDE console.

Number 0 occurs 0 times.
Number 1 occurs 1 times.
Number 2 occurs 4 times.
Number 3 occurs 1 times.
Number 4 occurs 1 times.
Number 5 occurs 1 times.

3. Use Maps

If the array elements are not in a fixed range or you need a more flexible solution, a Map (or HashMap in Java) can be used to count occurrences. This approach works well for any kind of data type, not just integers.

3.1 Code Example

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

public class CountWithMap {
    public static void main(String[] args) {
        // Initialize an array with some integer values
        int[] array = {
                1,
                2,
                2,
                3,
                4,
                2,
                5,
                2
        };

        // Create a HashMap to store the count of each integer
        Map<Integer, Integer> counterMap = new HashMap<>();

        // Loop through each element in the array
        for (int i : array) {
            // Update the count for the current element in the map
            counterMap.put(i, counterMap.getOrDefault(i, 0) + 1);
        }

        // Loop through the entries in the map to print the occurrences of each number
        for (Map.Entry<Integer, Integer> entry : counterMap.entrySet()) {
            // Print the result to the console
            System.out.println("Number " + entry.getKey() + " occurs " + entry.getValue() + " times.");
        }
    }
}

In this approach, we use a HashMap where the key is the element from the array and the value is the count of its occurrences. The getOrDefault method is used to fetch the current count of an element, and if it doesn’t exist, it returns 0. After iterating through the array, we print the results stored in the map.

The code prints the following output on the IDE console.

Number 1 occurs 1 times.
Number 2 occurs 4 times.
Number 3 occurs 1 times.
Number 4 occurs 1 times.
Number 5 occurs 1 times.

4. Use Java 8 Streams

With Java 8, the Streams API provides a concise and functional way to count occurrences in an array. This method is especially clean and expressive.

4.1 Code Example

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class CountWithStreams {
    public static void main(String[] args) {
        // Initialize an array with some integer values
        int[] array = {1, 2, 2, 3, 4, 2, 5, 2};

        // Use Java Streams to count occurrences of each integer in the array
        Map<Integer, Long> counterMap = Arrays.stream(array)
                // Convert the int stream to a stream of Integer objects
                .boxed()
                // Group by each integer and count occurrences
                .collect(Collectors.groupingBy(i -> i, Collectors.counting()));

        // Loop through the entries in the map to print the occurrences of each number
        counterMap.forEach((key, value) ->
                // Print the result to the console
                System.out.println("Number " + key + " occurs " + value + " times."));
    }
}

In this example, we use Arrays.stream(array) to create a stream of the array elements. We then box the primitive int values into Integer objects so that they can be used in a Map. The Collectors.groupingBy method is used to group the elements by their value and count their occurrences using Collectors.counting().

The code prints the following output on the IDE console.

Number 1 occurs 1 times.
Number 2 occurs 4 times.
Number 3 occurs 1 times.
Number 4 occurs 1 times.
Number 5 occurs 1 times.

5. Conclusion

Counting occurrences in an array can be accomplished in several ways depending on the complexity of the data and the specific requirements of your program. Whether you opt for a simple loop, an auxiliary array, a Map, or the power of Java 8 Streams, each method has its use case. Understanding these methods will help you select the most efficient approach for your particular scenario.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button