java 谓词_java8 in action:第一章学习,走进谓词(predicate)

好久都没有更新简书了,最近开始仔细学习java8。我属于那种不是特别聪明的程序员,一般都是买书,敲代码,看源码。很笨的学习方式。今天看了《java 8 in action》第一章,也顺便敲了敲代码。顺便分享一下其中的坑。

先上一个简单的demo。实体类Apple:

public class Apple {

private int weight = 0;

private String color = "";

public Apple(int weight, String color){

this.weight = weight;

this.color = color;

}

public Integer getWeight() {

return weight;

}

public void setWeight(Integer weight) {

this.weight = weight;

}

public String getColor() {

return color;

}

public void setColor(String color) {

this.color = color;

}

public String toString() {

return "Apple{" +

"color='" + color + '\'' +

", weight=" + weight +

'}';

}

}

通过list集合找出颜色为red的苹果。

public class Test1 {

public static void main(String[] args) {

List inventory=Arrays.asList(new Apple(10,"red"),

new Apple(100,"green"),

new Apple(200,"red"));

List redApples=filterApples(inventory,Test1::isRedApple);

System.out.println(redApples);

}

public static List filterApples(List inventory,Predicate p){

List result=new ArrayList();

for(Apple apple:inventory){

if(p.test(apple)){

result.add(apple);

}

}

return result;

}

public static boolean isRedApple(Apple apple){

return "red".equals(apple.getColor());

}

}

注意代码:

redApples=filterApples(inventory,Test1::isRedApple);

::表示方法。Test1::isRedApple就表示在Test1类下面的方法。

比如要查询重量大于100g的苹果:

先写判断的方法:

public static boolean isHeavyApple(Apple apple){

return apple.getWeight()>100;

}

再用predicate中去做筛选:

public static List filterHeavyApples(List inventory,Predicate p){

List result=new ArrayList();

for(Apple apple:inventory){

if(apple.getWeight()>100){

result.add(apple);

}

}

return result;

}

这样就可以看到结果了:

List heavyApples=filterApples(inventory,Test1::isHeavyApple);

System.out.println("大于100g的苹果:"+heavyApples);

好了接下来看下一下predicate的源码。

the type of the input to the predicate

**public interface Predicate **

predicate的参数为泛型。他的方法其实不多:

boolean test(T t);

default Predicate and(Predicate super T> other)

default Predicate negate()

default Predicate or(Predicate super T> other)

static Predicate isEqual(Object targetRef)

最常用的就是test这个方法。

default Predicate and(Predicate super T> other) 返回的正常的return (t) -> test(t) && other.test(t);

而认识negate这个单词就知道了:否定的意思,自然返回:

return (t) -> !test(t);

最后两个方法注意关键字or,isEqual就好。官方api的解释也不多。看看就知道什么意思了。

这里再将大于150g的苹果使用stream()的方式简写,使用lambda表达式:

//顺序处理:

List heavyApples2=inventory.stream().filter((Apple a) -> a.getWeight()>150)

.collect(toList());

System.out.println("大于100g的苹果01"+heavyApples2);

//并行处理

List heavyApples3=inventory.parallelStream().filter((Apple a) -> a.getWeight()>150)

.collect(toList());

System.out.println("大于100g的苹果02"+heavyApples2);

好了,今天就到这里了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值