Returns an Optional 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.This is a short-circuiting terminal operation.

1. Java Stream findfirst example with number

Here is example of find first even number from list of integers. In this example we have used List so stream() will return order stream.

java.util.List<Integer> list = Arrays.asList(1, 21, 4, 10, 36, 48, 47);     // its list of integer value
       Optional<Integer> integerOptional =                               // convert list to stream
                                               .filter(no -> no % 2 == 0)              // check number is even or not
                                               .findFirst();                           // findFirst will return first element, Once any even number find it will break loop.
       if (integerOptional.isPresent()) {
           System.out.println("Using Stream findFirst even number : " + integerOptional.get());


Using Stream findFirst even number : 4

2. Java Stream findfirst example

Here is example of find first developer from list of employee

java.util.List<Employee> employees = Employee.getEmployee();
       Optional<Employee> employeeOptional = employees
               .stream()                    // convert list to employee to stream
               .filter(employee -> employee.getDesignation()
                                           .equalsIgnoreCase("Developer"))        // find developer from list
               .findFirst();                           // it will return fist value from developer. once any developer will find it will break look it will not check for all elements
       if (employeeOptional.isPresent()) {
           System.out.println("Using Stream findFirst developer employee" + employeeOptional.get());


Using Stream findFirst developer employee:1 : Bob : Male : Developer


Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *