Java8--行为参数化

行为参数化,是我在《Java 8 实战》中学到的。下面举一个例子来说明什么是行为参数化。

现在要写一个过滤器对所有的苹果按照不同条件进行过滤:

  • 苹果实体类如下
public class Apple {
    private String color;
    private double weight;
    public Apple(String color, double weight) {
        this.color = color;
        this.weight = weight;
    }
    public String getColor() {
        return this.color;
    }
    public double getWeight() {
        return this.weight;
    }
    @Override
    public String toString() {
        return "color: " + this.color + ", weight: " + this.weight;
    }
}
public interface ApplePredicate {
    boolean test(Apple apple);
}
  • 测试类
public class Test {
    public static void main(String[] args) {
        Test t = new Test();
        List<Apple> aList = Arrays.asList(new Apple("red",3.4),
                new Apple("green",3.5),
                new Apple("red",4.2));
        // 无需去写接口的实现类,使用Lambda表达式即将整个方法作为参数传递,也就是行为参数化
        // 下面我用两种策略去过滤苹果,却都只需一行代码
        List<Apple> list1 = t.filterApples(aList, (a) -> a.getColor().equals("red") && a.getWeight() > 3.5);
        List<Apple> list2 = t.filterApples(aList, (a) -> a.getColor().equals("green"));
        System.out.println(list1);
        System.out.println(list2);
    }
    // 实现苹果的过滤
    public List<Apple> filterApples(List<Apple> aList,ApplePredicate predicate){
        List<Apple> list = new ArrayList<>();
        for(Apple a : aList) {
            if(predicate.test(a))
                list.add(a);
        }
        return list;
    }
}

其实我们之前使用匿名类也就是这里所说的行为参数化,不过我们现在使用Lambda表达式更简洁。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值