Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
