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


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

IntStream findFirst()返回描述此流的第一个元素的OptionalInt(一个可能包含也可能不包含非null值的容器对象),或者返回空的OptionalInt(如果该流为空)

用法:

OptionalInt findFirst()

Where, OptionalInt is a container object which
may or may not contain a non-null value 
and the function returns an OptionalInt describing the 
first element of this stream, or an empty OptionalInt
if the stream is empty. 

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


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

// Java code for IntStream findFirst() 
// which returns an OptionalInt describing 
// first element of the stream, or an 
// empty OptionalInt if the stream is empty. 
import java.util.*; 
import java.util.stream.IntStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating an IntStream 
        IntStream stream = IntStream.of(6, 7, 8, 9); 
  
        // Using IntStream findFirst() to return 
        // an OptionalInt describing first element 
        // of the stream 
        OptionalInt answer = stream.findFirst(); 
  
        // if the stream is empty, an empty 
        // OptionalInt is returned. 
        if (answer.isPresent())  
            System.out.println(answer.getAsInt());         
        else 
            System.out.println("no value");         
    } 
}

输出:

6

注意:如果流没有遇到顺序,则可以返回任何元素。

示例2:findFirst()方法返回第一个可被4整除的元素。

// Java code for IntStream findFirst() 
// which returns an OptionalInt describing 
// first element of the stream, or an 
// empty OptionalInt if the stream is empty. 
import java.util.OptionalInt; 
import java.util.stream.IntStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating an IntStream 
        IntStream stream = IntStream.of(4, 5, 8, 10, 12, 16) 
                               .parallel(); 
  
        // Using IntStream findFirst(). 
        // Executing the source code multiple times 
        // must return the same result. 
        // Every time you will get the same 
        // Integer which is divisible by 4. 
        stream = stream.filter(num -> num % 4 == 0); 
  
        OptionalInt answer = stream.findFirst(); 
        if (answer.isPresent())  
            System.out.println(answer.getAsInt());         
    } 
}

输出:

4


相关用法

注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 IntStream findFirst() in Java。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。