📜  Java中的 LongStream findFirst()

📅  最后修改于: 2022-05-13 01:54:49.168000             🧑  作者: Mango

Java中的 LongStream findFirst()

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

句法 :

OptionalLong findFirst()

参数 :

  1. OptionalLong :一个容器对象,它可能包含也可能不包含非空值。

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

注意: findAny() 是 Stream 接口的终端短路操作。此方法返回满足中间操作的任何第一个元素。

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