LongStream findFirst() method in Java

Java 8Object Oriented ProgrammingProgramming

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

The syntax is as follows.

OptionalLong findFirst()

Here, OptionalLong is a container object which may or may not contain a long value. For OptionalLong, import the following package.

import java.util.OptionalLong;

To use the LongStream class in Java, import the following package.

import java.util.stream.LongStream;

Create a LongStream and add elements.

LongStream longStream = LongStream.of(25000L, 35000L, 40000L, 50000L, 60000L);

Now, get the first element from the stream.

OptionalLong res = longStream.findFirst();

The following is an example to implement LongStream findFirst() method in Java.

Example

 Live Demo

import java.util.OptionalLong;
import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.of(25000L, 35000L, 40000L, 50000L, 60000L);
      OptionalLong res = longStream.findFirst();
      System.out.println("The first element of the stream: ");
      if (res.isPresent())
         System.out.println(res.getAsLong());
      else
         System.out.println("Nothing!");
   }
}

Output

The first element of the stream:
25000
raja
Published on 27-Mar-2019 10:04:11
Advertisements