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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * 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:
1 | 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:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: