Java 8 – Stream count() method with examples

In this article, we will discuss Stream’s count() method in details with examples

1. Stream count() method :

  • This Stream method is a terminal operation which counts number of elements present in the stream
  • Method signature :- long count()

2. Stream count() method examples :

2.1 To count number of elements present

  • First list contains first 10 natural numbers
  • Second list contains 5 String elements
  • We are going to count using Stream API and print to console
  • Note: this is very straight forward example and it can be counted using Collection API as well
  • We can use count() method after filtering and removing duplicates which is illustrated in the further examples

StreamCountMethod.java

package net.bench.resources.stream.count.example;

import java.util.Arrays;
import java.util.List;

public class StreamCountMethod {

	public static void main(String[] args) {

		// 1. list of 10 natural numbers
		List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

		// get count
		long count1 = numbers.stream().count();

		// print to console
		System.out.println("count of Numbers is = " + count1);

		// 2. list of 5 Strings
		List<String> sectors = Arrays.asList(
				"Motor", 
				"Power", 
				"Steel", 
				"Chemicals", 
				"Capital"
				);

		// get count
		long count2 = sectors.stream().count();

		// print to console
		System.out.println("count of String is = " + count2);
	}
}

Output:

count of Numbers is = 10
count of String is = 5

2.2 Count elements after filtering :

  • Count number of elements present after filtering even numbers from first 10 natural numbers
  • Similarly, count number of elements present whose character length is more than 5 from list of 5 String elements
  • We are going to count using Stream API and print to console

StreamCountAfterFilter.java

package net.bench.resources.stream.count.example;

import java.util.Arrays;
import java.util.List;

public class StreamCountAfterFilter {

	public static void main(String[] args) {

		// 1. list of 10 natural numbers
		List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

		// get count after filtering EVEN numbers
		long count1 = numbers.stream().filter(i -> i%2 == 0).count();

		// print to console
		System.out.println("count after filtering EVEN numbers = " + count1);

		// 2. list of 5 Strings
		List<String> sectors = Arrays.asList("Motor", "Power",
				"Steel", "Chemicals", "Capital");

		// get count after filtering length > 5
		long count2 = sectors.stream().filter(str -> str.length() > 5).count();

		// print to console
		System.out.println("count after filtering"
				+ " String length greater 5 = " + count2);
	}
}

Output:

count after filtering EVEN numbers = 5
count after filtering String length greater 5 = 2

2.3 Count elements after removing duplicates :

  • Count number of elements present after removing duplicates from list of integers
  • Similarly, count number of elements present after removing duplicates from list of String elements
  • We are going to count using Stream API and print to console

StreamCountDistinctElements.java

package net.bench.resources.stream.count.example;

import java.util.Arrays;
import java.util.List;

public class StreamCountDistinctElements {

	public static void main(String[] args) {

		// 1. list of integers
		List<Integer> numbers = Arrays.asList(
				1,
				2,2,
				3,3,3,
				4,4,4,4,
				5,5,5,5,5
				);

		// get count after removing duplicates
		long count1 = numbers.stream().distinct().count();

		// print to console
		System.out.println("count after removing duplicates"
				+ " from Integer elements = " + count1);

		// 2. list of Strings
		List<String> sectors = Arrays.asList(
				"Motor", 
				"Power",
				"Steel", 
				"Chemicals",
				"Chemicals",
				"Power",
				"Steel",
				"Capital",
				"TCS",
				"Motor", 
				"Power",
				"Communications"
				);

		// get count after removing duplicates
		long count2 = sectors.stream().distinct().count();

		// print to console
		System.out.println("count after removing duplicates"
				+ " from String elements = " + count2);
	}
}

Output:

count after removing duplicates from Integer elements = 5
count after removing duplicates from String elements = 7

2.4 Count elements for String starting with ‘T’ :

  • Count number of elements present for String starting with alphabet ‘T’
  • We are going to count using Stream API and print to console

StreamCountStartingElements.java

package net.bench.resources.stream.count.example;

import java.util.ArrayList;
import java.util.List;

public class StreamCountStartingElements {

	public static void main(String[] args) {

		// list of String elements
		List<String> companies = new ArrayList<>();
		companies.add("Tata Motor");
		companies.add("Tata Power");
		companies.add("Tata Steel");
		companies.add("Tata Chemicals");
		companies.add("Tata Capital");
		companies.add("Tata Sky");
		companies.add("Titan");
		companies.add("Birla");
		companies.add("Adani");
		companies.add("Reliance");
		companies.add("Mittal");

		// get count for companies starting with alphabet 'T'
		long count = companies
				.stream()
				.filter(company -> company.startsWith("T"))
				.count();

		// print to console
		System.out.println("count for companies "
				+ "starting with alphabet 'T' = " + count);
	}
}

Output:

count for companies starting with alphabet 'T' = 7

2.5 Count elements for repeated characters :

  • Count number of characters repeated in the given String
  • Here, we are going to pass character that needs to searched to find the count (or number of occurrences)
  • We are going to use intermediate operation filter() method for searching repeated/duplicate characters and then apply terminal method count() to find number of times its repeated

StreamCountRepeatedChars.java

package net.bench.resources.stream.count.example;

public class StreamCountRepeatedChars {

	public static void main(String[] args) {

		String str = "zzzAzzNzzzIzzY";
		char find = 'z';

		// original length
		System.out.println("Original length of String is " 
				+ str.length());

		// find count for character 'z'
		long count = str // original source
				.chars() // provides IntStream
				.filter(s -> s == find) // intermediate operation
				.count(); // terminal operation

		// print to console
		System.out.println("\nCharacter '" + find 
				+ "' repeated " + count + " times");
	}
}

Output:

Original length of String is 14

Character 'z' repeated 10 times

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream distinct() method with examples
Java 8 - Sorting List of primitive, String & Custom Objects