當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。