JAVA8学习---------1.2 JAVA中的函数

在Java 8里写下File::isHidden的时候,你就创建了一个方法引用,你同样可以传递它。

编写把函数作为一等值来传递的程序

  public static boolean isGreenApple(Apple apple) {
        return "green".equals(apple.getColor());
    }
    static List<Apple> filterApples(List<Apple> inventory,
            Predicate<Apple> p) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if (p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Apple> inventory = new ArrayList<>();
        Apple apple = new Apple();
        apple.setColor("green1");
        apple.setWeight(10);
        inventory.add(apple);
        //此处把isGreenApple方法作为参数传入 filterApples在执行test方法时会调用isGreenApple
        inventory = filterApples(inventory, AppleMethod::isGreenApple);
        System.out.println(inventory.size());

        //也可以现场使用lambda定义好需要使用的方法
        inventory = filterApples(inventory, (Apple a) -> 
        "green".equals(apple.getColor()));
        System.out.println(inventory.size());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值