Java Stream anyMatch()方法及例子

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

Java Stream anyMatch()方法及例子

流 anyMatch(Predicate predicate) 返回此流中是否有任何元素与提供的谓词相匹配。如果不是为了确定结果,它可能不会在所有元素上评估该谓词。这是一个 短路的终端操作 如果一个终端操作在面对无限的输入时,可能在有限的时间内终止,那么它就是短路的。
语法

boolean anyMatch(Predicate <? super T> predicate)

其中,T是输入到谓词的类型
的类型,如果流中有任何元素与所提供的谓词匹配,则该函数返回true。
匹配所提供的谓词。
否则为假。

注意: 如果流是空的,则返回false,谓词不被评估。
下面给出了一些例子,以更好地理解函数的实现。

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

// Java code for Stream anyMatch// (Predicate predicate) to check whether // any element of this stream match // the provided predicate.import java.util.*;  class GFG {          // Driver code    public static void main(String[] args) {              // Creating a list of Integers    List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);       // Stream anyMatch(Predicate predicate)     boolean answer = list.stream().anyMatch(n                     -> (n * (n + 1)) / 4 == 5);          // Displaying the result    System.out.println(answer);}}

输出:

true

例2: anyMatch()函数用于检查列表中是否有元素在第一个索引处有UpperCase。

// Java code for  Stream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a Stream of Strings        Stream<String> stream = Stream.of("Geeks", "fOr",                                          "GEEKSQUIZ", "GeeksforGeeks");          // Check if Character at 1st index is        // UpperCase in any string or not using        // Stream anyMatch(Predicate predicate)        boolean answer = stream.anyMatch(str -> Character.isUpperCase(str.charAt(1)));          // Displaying the result        System.out.println(answer);    }}

输出:

true

相关推荐