IntStream findFirst() method in Java


The findFirst() method in Java returns an OptionalInt describing the first element of this stream. If the stream is empty, an empty OptionalInt is returned.

The syntax is as follows

OptionalInt findFirst()

Here, OptionalInt is a container object which may or may not contain an int value.

To work with the IntStream class in Java, import the following package

import java.util.stream.IntStream;

For OptionalInt class, import the following package

import java.util.OptionalInt;

First, create an IntStream and add elements

IntStream intStream = IntStream.of(30, 45, 70, 80, 90, 120);

Now, get the first element of this stream

OptionalInt res = intStream.findFirst();

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

Example

 Live Demo

import java.util.OptionalInt;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(30, 45, 70, 80, 90, 120);
      OptionalInt res = intStream.findFirst();
      if (res.isPresent())
         System.out.println(res.getAsInt());
      else
         System.out.println("Nothing!");
   }
}

Output

30

Updated on: 30-Jul-2019

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements