count() Method Example In Java

The stream count() method is a part of terminal operations in java stream. The count() method returns the count of elements in the stream. The return type of count() method is long. It is the reduction process, it may traverse the stream to produce a result.

  1. The count() method is a part of terminal operations in java stream.
  2. The count() method returns the count of elements in the stream.
  3. The return type of count() method is long.
  4. It is the reduction process, it may traverse the stream to produce a result.
  5. You can use like list.stream().count().

Syntax:

 long count() 

Java Stream count() example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class CountMethodExample {
 public static void main(String args[]){
  //Declaring List
  List<Integer> intList = new ArrayList< Integer >();
  intList.add( 6 );
  intList.add( 11 );
  intList.add( 14 );
  intList.add( 7 );
  intList.add( 3 );
  intList.add( 2 );
  intList.add( 16 );
  intList.add( 15 );
  intList.add( 19 );

  //calling count method
  long count = intList.stream().count();

  System.out.println( count )
  
  }
}

Output:
    9

Java Stream count() with filter example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class CountMethodExample {
 public static void main(String args[]){
  //Declaring List
  List<Integer> intList = new ArrayList< Integer >();
  intList.add( 6 );
  intList.add( 11 );
  intList.add( 14 );
  intList.add( 7 );
  intList.add( 3 );
  intList.add( 2 );
  intList.add( 16 );
  intList.add( 15 );
  intList.add( 19 );

  long count = intList.stream()
                .filter(i -> i%2==0)
                .count(); //calling count method

  System.out.println( count )
  
  }
}

Output:
    4