How to get the first word in Java Stream?

How can we get the first word in a Java Stream ?

For example, we are given a stream of strings and one more word that we need to match in the stream and find out the first. What is the most easy and efficient way ?

You can do it by using filter and findFirst :

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args){
       Stream<String> resultStream = Arrays.asList("one", "two", "three", "four").stream();

       Optional firstValue = resultStream.filter(x -> x.equals("four")).findFirst();

       if(firstValue.isPresent()){
           System.out.println(firstValue.get());
       }
    }
}

filter is used to filter out items that are equal to a given string and findFirst return the first element from the stream.