Java IntStream allMatch()示例

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

Java IntStream allMatch()示例

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

语法

boolean allMatch(IntPredicate predicate)

其中,IntPredicate代表一个谓词(布尔值函数)。
的一个int值参数,并且该函数在以下两种情况下返回true
流中的所有元素与提供的谓词相匹配,或者
流是空的,否则为假。

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

例1: allMatch()函数用于检查所有元素是否都能被3整除。

// Java code for IntStream allMatch// (Predicate predicate) to check whether// all elements 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(3, 5, 9, 12, 14);          // Check if all elements of stream        // are divisible by 3 or not using        // IntStream allMatch(Predicate predicate)        boolean answer = stream.allMatch(num -> num % 3 == 0);          // Displaying the result        System.out.println(answer);    }}

输出:

false

例2: allMatch()函数用于检查两个IntStream串联后得到的IntStream中的所有元素是否都小于2。

// Java code for IntStream allMatch// (Predicate predicate) to check whether// all elements 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 after concatenating        // two IntStreams        IntStream stream = IntStream.concat(IntStream.of(-2, -4, -6, -8),                                            IntStream.of(-1, 0, 1, 5));          // Check if all elements of stream        // are less than 2 or not using        // IntStream allMatch(Predicate predicate)        boolean answer = stream.allMatch(num -> num < 2);          // Displaying the result        System.out.println(answer);    }}

输出:

false

例3: allMatch()函数显示如果流是空的则返回true。

// Java code for IntStream allMatch// (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.allMatch(num -> true);          // Displaying the result        System.out.println(answer);    }}

输出:

true

相关推荐