Java 8 Stream Count Occurrences

We often have a need to count the occurrences of an integer or a string within an Array, List, or ArrayList. With the introduction of Java 8 Streams, this task is quite easy and simple to accomplish.

Below you will find two tutorials. The first example will search for a String and count number of times it was found in the ArrayList. The second example will search an Integer and count number of times it was found in the ArrayList.

Count Occurrences String

The following sample code defines and populates an ArrayList of Strings, creates a stream(), applies a filter(), and then calls count() operation. Basically finds the number of times “Java” was found in the ArrayList.

//JavaCodeDepot Sample

List<String>jcdList = new ArrayList<String>(Arrays.asList("Java","Code","Depot","Samples","Snippet","Java"));

long jcdCount = jcdList
	.stream()
	.filter(p -> p.equals("Java"))
	.count();
	    
System.out.println("Found Java "+jcdCount+" Times");

Output:

Found Java 2 Times


Count Occurrences Integer

The following sample code defines and populates an ArrayList of Integers, creates a stream(), applies a filter(), and then calls count() operation. Basically finds the number of times “22” was found in the ArrayList.

//JavaCodeDepot Sample

List<Integer>jcdIntList = new ArrayList<Integer>(Arrays.asList(10, 20, 22, 33, 44, 22, 55, 66, 34, 78, 83, 22));

long jcdIntCount = jcdIntList
	.stream()
	.filter(i -> i == 22)
	.count();
	  	    
System.out.println("Found 22 "+jcdIntCount+" Times");

Output:

Found 22 3 Times


Add a Comment

Your email address will not be published. Required fields are marked *