Java DoubleStream findFirst()的例子

来源:这里教程网 时间:2026-02-17 20:49:36 作者:

Java DoubleStream findFirst()的例子

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

语法:

OptionalDouble findFirst()

参数

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

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

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

Example 1 : 在Double Stream上的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

相关推荐