Java 8 Stream - count(), findAny(), findFirst(), max() and min() example

Posted on January 12, 2017


In this post, we learn how to use the count(), findAny(), findFirst(), max() and min() methods of the java.util.stream.Stream interface in java program.

count() - This method returns the count of elements of a stream.

findAny() - This method returns an java.util.Optional  describing some element of the stream, or an empty java.util.Optional if the stream is empty.

findFirst() - This method  returns an java.util.Optional describing the first element of this stream, or an empty java.util.Optional if the stream is empty.

max() - This method  returns the maximum element of a stream according to the provided Comparator.

min() -  This method  returns the minimum element of a stream according to the provided Comparator.

The following example demonstrates the use of the count(), findAny(), findFirst(), max() and min() methods.

StreamExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 */
public class StreamExample {
  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);

    // Count
    long count = numbers.stream().count();
    System.out.println("Count : " + count);

    // Find Any
    Integer findEle = numbers.stream()
        .findAny()
        .get();
    System.out.println("FindAny : " + findEle);

    // Find First
    Integer findFirstEle = numbers.stream()
        .findFirst()
        .get();
    System.out.println("FindFirst : " + findFirstEle);

    // Max
    Integer max = numbers.stream()
        .max((a, b) -> a - b)
        .get();
    System.out.println("Max : " + max);

    // Min
    Integer min = numbers.stream()
        .min((a, b) -> a - b)
        .get();
    System.out.println("Min : " + min);

  }
}

Output

Count : 6
FindAny : 1
FindFirst : 1
Max : 5
Min : 1