java match_Java Stream anyMatch()用法及代码示例

流anyMatch(谓词谓词)返回此流的任何元素是否与提供的谓词匹配。如果不一定要确定结果,则可能不会评估所有元素上的谓词。这是短路端子操作。如果出现无限输入时,端子操作可能会在有限时间内终止,则该端子操作会发生短路。

用法:

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: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 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 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值