OneCompiler

[Java] How to find the total number of occurrences of an element in an array?

I want to find how many times a given element present in an array, how can I do that in Java?

1 Answer

4 years ago by

Using streams

Easiest way to find the total occurrences of the given element from an array is using Java streams, following code shows how to do that.

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		int[] numbers = { 45, 22, 67, 90, 22, 78, 22 };		
		int occurrences = Arrays.stream(numbers).filter(ele -> ele == 22).toArray().length;
		System.out.printf("Total occurrences of element %d is: %d ", 22, occurrences);
	}
}

Output:

Total occurrences of element 22 is: 3

Try online here: https://onecompiler.com/java/3xmsuj5ey

Not using streams (to work with JDK < 8)

We can loop through the given array and compare the elements in the array with the given element to find the total number of occurrences. Following code shows that

public class JavaArrays {
	public static void main(String[] args) {
		int[] numbers = { 45, 22, 67, 90, 22, 78, 22 };
		System.out.printf("Total occurrences of element %d is: %d ", 22, totalOccurrences(numbers, 22));
	}

	static int totalOccurrences(int[] array, int element) {
		int count = 0;
		for (int ele : array) {
			if (ele == element) {
				count++;
			}
		}

		return count;
	}
}

Output

Total occurrences of element 22 is: 3

Try online here: https://onecompiler.com/java/3xmsu9rw2

4 years ago by Karthik Divi