Open In App

Stream findFirst() in Java with examples

Last Updated : 06 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

Syntax :

Optional<T> findFirst()

Where, Optional is a container object which
may or may not contain a non-null value 
and T is the type of objects and the function
returns an Optional describing the first element 
of this stream, or an empty Optional if the stream is empty.

Exception : If the element selected is null, NullPointerException is thrown.

Note : findAny() is a terminal-short-circuiting operation of Stream interface. This method returns first element satisfying the intermediate operations.

Example 1 : findFirst() function on Stream of Integers.




// Java code for Stream findFirst()
// which returns an Optional describing
// the first element of this stream, or
// an empty Optional if the stream is empty.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a List of Integers
        List<Integer> list = Arrays.asList(3, 5, 7, 9, 11);
  
        // Using Stream findFirst()
        Optional<Integer> answer = list.stream().findFirst();
  
        // if the stream is empty, an empty
        // Optional is returned.
        if (answer.isPresent()) {
            System.out.println(answer.get());
        }
        else {
            System.out.println("no value");
        }
    }
}


Output :

3

Example 2 : findFirst() function on Stream of Strings.




// Java code for Stream findFirst()
// which returns an Optional describing
// the first element of this stream, or
// an empty Optional if the stream is empty.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a List of Strings
        List<String> list = Arrays.asList("GeeksforGeeks", "for",
                                          "GeeksQuiz", "GFG");
  
        // Using Stream findFirst()
        Optional<String> answer = list.stream().findFirst();
  
        // if the stream is empty, an empty
        // Optional is returned.
        if (answer.isPresent()) {
            System.out.println(answer.get());
        }
        else {
            System.out.println("no value");
        }
    }
}


Output :

GeeksforGeeks


Previous Article
Next Article

Similar Reads

DoubleStream findFirst() with examples
DoubleStream findFirst() returns an OptionalDouble (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty OptionalDouble if the stream is empty. Syntax : OptionalDouble findFirst() Parameters : OptionalDouble : A container object which may or may not contain a non-null value. Retu
2 min read
IntStream findFirst() in Java
IntStream findFirst() returns an OptionalInt (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty OptionalInt if the stream is empty Syntax : OptionalInt findFirst() Where, OptionalInt is a container object which may or may not contain a non-null value and the function returns a
2 min read
LongStream findFirst() in Java
LongStream findFirst() returns an OptionalLong (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty OptionalLong if the stream is empty Syntax : OptionalLong findFirst() Parameters : OptionalLong : A container object which may or may not contain a non-null value. Return Value :
2 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
Java Program to Convert String to Char Stream Without Using Stream
Char stream defines the array of characters. In this article, we will learn the different types of methods for converting a String into a char stream in Java without using Stream. Let us see some methods one by one. ExamplesInput: String = HelloGeeksOutput: [H, e, l, l, o, G, e, e, k, s] Input: String = Introduction Output: [I, n, t, r, o, d, u, c,
4 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.reduce() in Java with examples
Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previou
3 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read