In  this tutorial, we will see “How to count occurrences of a specific number in an array using Java 8 Streams?”

Count occurrences of a number using Java 8 Streams API

Java 8 – How to count occurrences of a number in an array using Streams? Share on X

/**
 * Find the count of occurrences of a specific number in an Array using Java 8 
 * @author Deepak Verma
 *
 */

import java.util.Arrays;

public class Count_Occurrences_of_a_number_In_Array_Using_Java8 {

	public static void main(String[] args) {

		int[] arrayOfNumbers = {99, 2, 37, 88, 35, 99, 37, 62, 24, 1, 73, 99};
	    
		int targetNumber = 99;

	    long countOfTheTargetNumber = Arrays.stream(arrayOfNumbers)
	                                        .filter(x -> x == targetNumber)
	                                        .count();
	    System.out.println("The number " + targetNumber + " occurs " + countOfTheTargetNumber + " times in the array:"+Arrays.toString(arrayOfNumbers));
	  
	}

}

 

Output:

The number 99 occurs 3 times in the array:[99, 2, 37, 88, 35, 99, 37, 62, 24, 1, 73, 99]

Count occurrences of a number using Java 8 Streams API

In the above example, The arrayOfNumbers is an array of integers basically, and the targetNumber is the number to count occurrences of. The Arrays.stream method of Java 8 is used to create a stream from the array, and then the filter method is used to filter the stream to only include elements that are equal to the specified target number. Finally, The count method returns the number of elements in the filtered stream, which is the number of times the target number occurs in that particular array.

Java 8 – How to count occurrences of a number in an array using Streams? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts