January 15, 2024

Java Stream count() With Examples

In Java Stream API there is a count() method that returns the count of elements in the stream. In this tutorial you’ll learn about count() method with the help of some examples.

Java Stream count() method

Syntax of the count() method is as follows-

long count()

count method is a special case of a reduction operation as it takes a sequence of input elements and combines them into a single summary result. This method is a terminal operation meaning it produces a result and stream pipeline is considered consumed, and can no longer be used after count operation.

count() method Java examples

1. Using count() to get the number of elements in a List by using list as a Stream source.

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

public class CountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(3, 5, 4, 12, 16, 0, 7, 6);
    long result = numList.stream().count();
    System.out.println("Number of elements- " + result);
  }
}
Output
Number of elements- 8

2. You can also use count() method along with other operations to get the count of stream elements after applying other operations. In the following example first filter() method is used to filter out elements as per the given condition (elements should be greater than 10) then count() is used to get the count of elements in the stream after applying filter operation.

public class CountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(3, 5, 4, 12, 16, 0, 7, 6);
    long result = numList.stream().filter(e -> e > 10).count();
    System.out.println("Number of elements- " + result);
  }
}
Output
Number of elements- 2

3. In the following example count() is used to get the count of distinct elements.

public class CountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(3, 5, 5, 12, 16, 12, 3, 6);
    long result = numList.stream().distinct().count();
    System.out.println("Number of elements- " + result);
  }
}
Output
Number of elements- 5

That's all for the topic Java Stream count() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment