Java Stream findFirst() with examples

 226 total views,  2 views today

Welcome to Java 8 series. In this tutorial, you will learn about java stream findFirst() with examples.

findFirst() is a part of the Stream pipeline and terminal operation. It belongs to the Stream interface.

findFirst() allows us to get the first element of the stream. Once findFirst() is invoked on a stream, it returns the first element of the stream and the stream will be closed. We cannot reuse the stream as we have invoked a terminal operation i.e., findFirst().

If the stream is empty, findFirst() will return an empty optional.

Method Description

Optional<T> findFirst()

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

Let us now see a few examples of Java 8 stream findFirst()

Java stream findFirst() operation example

public class StaticReference
{
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(2);
        list.add(3);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);

        Optional<Integer> result = list.stream().findFirst();

        System.out.println("FindFirst Integer : " + result.get());
     }

}

Output

FindFirst Integer : 10

Java stream findFirst() operation example – String

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> listString = new ArrayList<>();
        listString.add("q");
        listString.add("b");
        listString.add("c");
        listString.add("d");

        Optional<String> output = listString.stream().findFirst();

        System.out.println("FindFirst String : " + output.get());
    }
}

Output

FindFirst String : q

Java stream findFirst() operation empty stream example

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> listString = new ArrayList<>();

        Optional<String> output = listString.stream().findFirst();

        if (output.isPresent())
        {
            System.out.println("FindFirst String : " + output.get());
        }
        else
        {
            System.out.println("Stream is empty");
        }
    }
}

Output

Stream is empty

Conclusion

findFirst() operation is a terminal operation and it is used for getting the first element in the stream.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.