Java Stream findFirst()示例

来源:这里教程网 时间:2026-02-17 21:12:15 作者:

Java Stream findFirst()示例

Stream findFirst() 返回一个Optional(一个容器对象,可以包含也可以不包含一个非空值),描述这个流的 第一个 元素,如果流是空的,则返回一个空的Optional。如果该流没有相遇顺序,那么任何元素都可以被返回。

语法:

Optional <T> findFirst()

其中,Optional是一个容器对象,它 可能包含也可能不包含一个非空值 和T是对象的类型,函数 返回一个描述该流的第一个元素的Optional 的第一个元素,如果该流是空的,则返回一个空的Optional。

异常: 如果选择的元素是空的,会抛出 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<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");        }    }}

输出:

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<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");        }    }}

输出:

GeeksforGeeks

相关推荐