📜  DoubleStream findFirst() 示例

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

DoubleStream findFirst() 示例

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

句法 :

OptionalDouble findFirst()

参数 :

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

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

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

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

// Java code for DoubleStream findFirst()
// which returns an OptionalDouble describing
// first element of the stream, or an
// empty OptionalDouble if the stream is empty.
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream
        DoubleStream stream = DoubleStream.of(6.2, 7.3, 8.4, 9.5);
  
        // Using DoubleStream findFirst() to return
        // an OptionalDouble describing first element
        // of the stream
        OptionalDouble answer = stream.findFirst();
  
        // if the stream is empty, an empty
        // OptionalDouble is returned.
        if (answer.isPresent())
            System.out.println(answer.getAsDouble());
        else
            System.out.println("no value");
    }
}

输出 :

6.2

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

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

// Java code for DoubleStream findFirst()
// which returns an OptionalDouble describing
// first element of the stream, or an
// empty OptionalDouble if the stream is empty.
import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream
        DoubleStream stream = DoubleStream.of(4.7, 4.5, 
                    8.0, 10.2, 12.0, 16.0).parallel();
  
        // Using DoubleStream findFirst().
        // Executing the source code multiple times
        // must return the same result.
        // Every time you will get the same
        // Double value which is divisible by 4.
        stream = stream.filter(num -> num % 4.0 == 0);
  
        OptionalDouble answer = stream.findFirst();
        if (answer.isPresent())
            System.out.println(answer.getAsDouble());
    }
}

输出 :

8.0