Java IntStream anyMatch()示例

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

Java IntStream anyMatch()示例

IntStream anyMatch(IntPredicate predicate) 返回此流的 任何 元素是否与提供的谓词相匹配。如果不是确定结果所必需的,它可能不会在所有元素上评估该谓词。这是一个 短路的终端操作。 如果一个终端操作在遇到无限的输入时,可以在有限的时间内结束,那么它就是短路的。

语法

boolean anyMatch(IntPredicate predicate)

其中,IntPredicate代表一个谓词(布尔值函数)。
的一个int值参数,如果流中有任何元素与所提供的predicate匹配,则该函数返回true。
流中的元素与所提供的谓词相匹配,则函数返回true。
否则为假。

注意: 如果流是空的,那么返回false,谓词不被评估。

例1: anyMatch()函数用于检查列表中的任何元素是否满足给定条件。

// Java code for IntStream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.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(1, 2, 3, 4, 5, 6);          // Stream anyMatch(Predicate predicate)        boolean answer = stream.anyMatch(num -> (num - 5) > 0);          // Displaying the result        System.out.println(answer);    }}

输出:

true

例2: anyMatch()函数用于检查流中任何元素的平方根是否大于8。

// Java code for IntStream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.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(10, 20, 30, 40, 50);          // Stream anyMatch(Predicate predicate)        boolean answer = stream.anyMatch(num -> Math.sqrt(num) > 8);          // Displaying the result        System.out.println(answer);    }}

输出:

false

例3: anyMatch()函数显示,如果流是空的,则返回false。

// Java code for IntStream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.import java.util.*;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating an empty IntStream        IntStream stream = IntStream.empty();          boolean answer = stream.anyMatch(num -> true);          // Displaying the result        System.out.println(answer);    }}

输出:

false

相关推荐