Java中的Stream anyMatch()及其示例

流anyMatch(谓词) 返回此流的任何元素是否与提供的谓词匹配。如果不是确定结果所必需的,它可能不会对所有元素的谓词求值。这是一个 短路终端操作。 如果终端操作在无限输入时可能在有限时间内终止,则终端操作为短路。 语法:

null
boolean anyMatch(Predicate<? super T> predicate)

Where, T is the type of the input to the predicate
and the function returns true if any elements of
the stream match the provided predicate, 
otherwise false.

注: 如果流为空,则返回false,并且不计算谓词。 下面给出一些例子,以更好地理解函数的实现。

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

// 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: 函数的作用是:检查列表中第一个索引是否有大写的元素。

// 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
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享