当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stream findFirst()用法及代码示例


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

用法:

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

异常:如果所选元素为null,则抛出NullPointerException。


注意:findAny()是流接口的terminal-short-circuiting操作。此方法返回满足中间操作的第一个元素。

示例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


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream findFirst() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。