📜  在Java中使用示例流 findFirst()

📅  最后修改于: 2022-05-13 01:54:22.314000             🧑  作者: Mango

在Java中使用示例流 findFirst()

Stream findFirst()返回描述此流的第一个元素的 Optional(可能包含或不包含非 null 值的容器对象),如果流为空,则返回空 Optional。如果流没有遇到顺序,则可以返回任何元素。

句法 :

Optional 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.

异常:如果选择的元素为空,则抛出NullPointerException

注意: findAny() 是 Stream 接口的终端短路操作。此方法返回满足中间操作的第一个元素。

示例 1:整数流上的 findFirst()函数。

// 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 list = Arrays.asList(3, 5, 7, 9, 11);
  
        // Using Stream findFirst()
        Optional 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");
        }
    }
}

输出 :

3

示例 2:字符串流上的 findFirst()函数。

// 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 list = Arrays.asList("GeeksforGeeks", "for",
                                          "GeeksQuiz", "GFG");
  
        // Using Stream findFirst()
        Optional 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");
        }
    }
}

输出 :

GeeksforGeeks