Open In App

Java - Counting Number of Occurrences of a Specified Element in an Array

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, arrays are used to store multiple elements of the same type in a single variable. Sometimes, we may need to count how many times a specific value appears in an array, like tracking survey responses, votes, or repeated patterns in data. In this article, we will learn simple methods to count occurrences of an element in an array.

Example: The simplest way to count occurrences is to loop through the array and increment a counter whenever the target element is found.

Java
// Java Program to Count the Number of Occurrences 
// of a Specified Element in an Array
public class CountOccurrences {

    public static void main(String[] args) {
      
        int[] arr = {1, 2, 3, 2, 1, 2, 4};    // Example array
        int t = 2;     // Element to count

        int c = 0;   // Initialize count to 0
        for (int num : arr) {    // Iterate over the array
            if (num == t) {    // Check if the current element matches the target
                c++;    // Increment count
            }
        }

        System.out.println("Element " + t + " occurs " + c + " times in the array.");
    }
}

Output
Element 2 occurs 3 times in the array.

Explanation: In the above example, it iterates through the array and counts each occurrence of the target element. This is a straightforward solution that is easy to understand.

Other Methods to Count Occurrences of a Element in an Array

1. Using a Utility Function

Encapsulating the logic in a utility function makes the code reusable and cleaner. The function takes an array and the target element as inputs and returns the count of occurrences.

Java
// Java Program to Count Occurrences 
// Using a Utility Function

public class CountOccurrences {

    // Utility method to count occurrences of 
    // a target element in an array
    public static int count(int[] arr, int t) {
        if (arr == null) {       // Check if the array is null
            return 0;       // Return 0 if array is null
        }
        int c = 0;     // Initialize count
        for (int num : arr) {
            if (num == t) {      // Check for matching elements
                c++;      // Increment count
            }
        }
        return c;
    }

    public static void main(String[] args) {
      
        int[] n = {10, 20, 30, 20, 10, 20, 50};
        int t = 20;

        // Use the utility method to count occurrences
        int o = count(n, t);
        System.out.println("Element " + t + " occurs " + o + " times in the array.");
    }
}

Output
Element 20 occurs 3 times in the array.

Explanation: In the above example, the count method checks for null arrays and counts occurrences of the target element. This approach is reusable across multiple use cases.

2. Using Streams (Java 8+)

In Java 8, the Stream API provides a concise way to count occurrences of an element in an array.

Java
// Java Program to Count Occurrences 
// Using Streams
import java.util.stream.IntStream;

public class CountOccurrences {
  
    public static void main(String[] args) {
      
        int[] n = {10, 20, 30, 20, 10, 20, 50};
        int t = 20;

        // Use Streams API to count occurrences
        long c = IntStream.of(n)   // Create a stream from the array
                              .filter(num -> num == t) // Filter elements matching the target
                              .count();     // Count matching elements

        System.out.println("Element " + t + " occurs " + c + " times in the array.");
    }
}

Output
Element 20 occurs 3 times in the array.

Explanation: In the above example, the IntStream.of(n) creates a stream of the array, and .filter() filters elements matching the target. The .count() method calculates the number of filtered elements.

3. Using Collections.frequency() for Non-Primitive Arrays

For non-primitive arrays (like String or Integer), we can convert the array to a List and use Collections.frequency() to count the occurrences of an element.

Java
// Java Program to Count Occurrences 
// Using Collections.frequency
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CountOccurrences {
  
    public static void main(String[] args) {
      
        String[] n = {"A", "B", "C", "D", "B"};
        String t = "B";

        // Convert the array to a List
        List<String> l = Arrays.asList(n);

        // Use Collections.frequency to count occurrences
        int c = Collections.frequency(l, t);

        System.out.println("Element \"" + t + "\" occurs " + c + " times in the array.");
    }
}

Output
Element "B" occurs 2 times in the array.

Explanation:In the above example, theArrays.asList(names) converts the array to a List and theCollections.frequency() counts the number of occurrences of the specified element in the list.