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


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


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

用法:

OptionalLong findFirst()

参数:


  1. OptionalLong : 可以包含或不包含非null值的容器对象。

返回值:该函数返回描述此流的第一个元素的OptionalLong;如果流为空,则返回一个空的OptionalLong。

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

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

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

输出:

6

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

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

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

输出:

4


相关用法


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