是时候了解一下 Java 8 新增的函数式接口 Predicate 了

Predicate 是 Java 8 新增的一个函数式接口(通过 @FunctionalInterface 注解定义),因此可以将一个 Lambda 表达式赋值于它。

来看这样一个例子:

Predicate<Integer> noGreaterThan5 = x -> x > 5;

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> collect = list.stream()
        .filter(noGreaterThan5)
        .collect(Collectors.toList());

System.out.println(collect); // [6, 7, 8, 9, 10]

还可以使用 and() 方法对条件进行拼接:

Predicate<Integer> noGreaterThan5 = x -> x > 5;
Predicate<Integer> noLessThan8 = x -> x < 8;

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> collect = list.stream()
        .filter(noGreaterThan5.and(noLessThan8))
        .collect(Collectors.toList());

System.out.println(collect); // [6, 7]

除了 and(),还有 or

Predicate<String> lengthIs3 = x -> x.length() == 3;
Predicate<String> startWithA = x -> x.startsWith("A");

List<String> list = Arrays.asList("A", "AA", "AAA", "B", "BB", "BBB");

List<String> collect = list.stream()
        .filter(lengthIs3.or(startWithA))
        .collect(Collectors.toList());

System.out.println(collect); // [A, AA, AAA, BBB]

还有 negate()(相反):

Predicate<String> startWithA = x -> x.startsWith("A");

List<String> list = Arrays.asList("A", "AA", "AAA", "B", "BB", "BBB");

List<String> collect = list.stream()
        .filter(startWithA.negate())
        .collect(Collectors.toList());

System.out.println(collect); //[B, BB, BBB]

再来看一下 test()

Predicate<String> startWithA = x -> x.startsWith("王");

// 以王或者沉开头
boolean result = startWithA.or(x -> x.startsWith("沉")).test("沉默王二");
System.out.println(result);     // true

PS:本篇文章中的示例代码已经同步到码云,传送门~

原创不易,喜欢就点个赞,因为你一个小小的举动,就会让这个世界多一份美好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值