Java Streams - LongStream findFirst() example








LongStream findFirst() returns an OptionalLong describing the first element of this stream, or an empty OptionalLong if the stream is empty.

Syntax

findFirst has the following syntax.

OptionalLong findFirst()

Example

The following example shows how to use findFirst.

import java.util.OptionalLong;
import java.util.stream.LongStream;
/*from  w  ww.  j  ava  2  s. c om*/
public class Main {
  public static void main(String[] args) {
    LongStream b = LongStream.of(1L, 2L, Long.MAX_VALUE, Long.MIN_VALUE);
    OptionalLong o = b.findFirst();
    
    if(o.isPresent()){
      System.out.println(o.getAsLong()); 
    }else{
      System.out.println("no value");
    }
  }
}

The code above generates the following result.