Streams – count() operation

The Stream count() method in Java returns the total count of elements in the Stream. It is a terminal operation, so we can not perform any other operation after it. It accepts a stream of elements and returns a long, representing the total count of elements.

Java Stream count() operation – examples

Example 1:

Get the total count of numbers in the list:

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 7, 9, 22, 19, 18, 47, 3, 12, 29, 17, 44, 78, 99));

    long totalCount = numbers.stream().count();

    System.out.println("Total count of numbers: " + totalCount);
  }
}

Output: Total count of numbers: 14

Example 2:

Get the total count of custom objects in a list:

class Student {
  private String firstName;
  private String lastName;
  private int grade;

  public Student(String firstName, String lastName, int grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }
}

class Test {

  public static void main(String[] args) {
    List<Student> students = getStudents();

    long totalCount = students.stream().count();

    System.out.println("Total count of students: " + totalCount);
  }
  
  private static List<Student> getStudents() {
    List<Student> students = new ArrayList<>();
    students.add(new Student("Steve", "Rogers", 8));
    students.add(new Student("John", "Doe", 5));
    students.add(new Student("Melissa", "Smith", 7));
    students.add(new Student("Megan", "Norton", 4));
    students.add(new Student("Tom", "Johnson", 9));

    return students;
  }
}

Output: Total count of students: 5

I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

 

Leave a Reply

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