📜  IntStream findAny() 示例

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

IntStream findAny() 示例

IntStream findAny()返回描述流的某些元素的OptionalInt (可能包含或不包含非空值的容器对象),如果流为空,则返回空的 OptionalInt。

句法 :

OptionalInt findAny()

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

注意: findAny() 是 Stream 接口的终端短路操作。此方法返回满足中间操作的任何第一个元素。这是一个短路操作,因为它只需要返回“任何”第一个元素并终止其余的迭代。

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

// Java code for IntStream findAny()
// which returns an OptionalInt describing
// some 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 findAny() to return
        // an OptionalInt describing some element
        // of the stream
        OptionalInt answer = stream.findAny();
  
        // 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

注意: IntStream findAny() 操作的行为是明确的非确定性的,即可以自由选择流中的任何元素。对同一源的多次调用可能不会返回相同的结果。

示例 2: findAny() 方法以不确定的方式返回可被 4 整除的元素。

// Java code for IntStream findAny()
// which returns an OptionalInt describing
// some 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 findAny().
        // Executing the source code multiple times
        // may not return the same result.
        // Every time you may get a different
        // Integer which is divisible by 4.
        stream = stream.filter(num -> num % 4 == 0);
  
        OptionalInt answer = stream.findAny();
        if (answer.isPresent()) {
            System.out.println(answer.getAsInt());
        }
    }
}

输出 :

16