Java - Counting Number of Occurrences of a Specified Element in an Array
Last Updated :
09 Dec, 2024
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.");
}
}
OutputElement 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.");
}
}
OutputElement 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.");
}
}
OutputElement 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.");
}
}
OutputElement "B" occurs 2 times in the array.
Explanation:
In the above example, the
Arrays.asList(
names) c
onverts the array to a List and the
Collections.frequency()
counts the number of occurrences of the specified element in the list.
Similar Reads
How to Find Length or Size of an Array in Java? Finding the length of an array is a very common and basic task in Java programming. Knowing the size of an array is essential so that we can perform certain operations. In this article, we will discuss multiple ways to find the length or size of an array in Java.In this article, we will learn:How to
3 min read
Queries to print count of distinct array elements after replacing element at index P by a given element Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array. Examples: Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6,
14 min read
Java Program to Find the Number Occurring Odd Number of Times Write a Python program for a given array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space. Examples : Input: arr = {1, 2, 3, 2, 3, 1, 3}Output : 3 Input: arr = {5, 7, 2, 7, 5, 2, 5
4 min read
Java Program to Find the Length/Size of an ArrayList Given an ArrayList in Java, the task is to write a Java program to find the length or size of the ArrayList. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: 5 Input: ArrayList: [geeks, for, geeks] Output: 3 ArrayList - An ArrayList is a part of the collection framework and is present in java.uti
2 min read
Stream count() method in Java with examples long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may travers
2 min read