Java8 特性笔记(一) 引入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jeekmary/article/details/87997328

lamdb是java8里面一个比较重要的技术更新,我们需要了解他 掌握它,这样在我门以后的开发中会极大的提高我们的工作效率

1,首先我们来看 java8 in Action这本书中的一段话

Writing code that can cope with changing requirements is difficult. Let’s walk through an example that we’ll gradually improve, showing some best practices for making your code more flexible. In the context of a farm-inventory application, you have to implement a functionality to filter green apples from a list. Sounds easy, right?

也就是说让我们在一对类里面找出符合条件的类,通过这个例子引入吧

2,比较死的方法

    public static List<Apple> findGreenApple(List<Apple> apples){
        List<Apple> list = new ArrayList<>();
        for (Apple apple:apples){
            if (apple.getColor().equals("green")){
                list.add(apple);
            }
        }
        return list;
    }
        List<Apple> list = Arrays.asList(new Apple("green",120),new Apple("red",150),new Apple("yellow",140),new Apple("green",130));
        List<Apple> greenApples = findGreenApple(list);

像上面这样调用就可以,但是这样的话代码就比较死板,有没有另外的办法呢?

3,给函数动态参数


    public static List<Apple> findApple(List<Apple> apples, String color){
        List<Apple> list = new ArrayList<>();
        for (Apple apple:apples){
            if (apple.getColor().equals(color)){
                list.add(apple);
            }
        }
        return list;
    }

这里我们在需要过滤的时候可以将颜色一起传过去,就能达到很好的效果,更灵活一点

4,通过接口来过滤

    public interface AppleFilter{
        boolean filter(Apple apple);
    }
    public static List<Apple>  findApple(List<Apple> apples, AppleFilter appleFilter){
        List<Apple> list = new ArrayList<>();
        for (Apple apple:apples){
            if (appleFilter.filter(apple)){
                list.add(apple);
            }
        }
        return list;
    }

这里我们定义一个接口,这个接口里面返回的是boolean值,我们在这个方法里面调用接口的方法,这样一来我们把条件给暴露出来,用户只需要把过滤的条件写出来就可以了

 public static class GreenAnd120WeightFilter implements AppleFilter{

        @Override
        public boolean filter(Apple apple) {
            return (apple.getColor().equals("green")&&apple.getWeight()>120);
        }
    }

这里我们定义了一个类,在这个类里面我们实现了上面的接口,编写了过滤的条件

// 调用,发现效果很好
       List<Apple> apple = findApple(list, new GreenAnd120WeightFilter());
        System.out.println(apple);

4,通过匿名内部类

List<Apple> apple1 = findApple(list, new AppleFilter() {
            @Override
            public boolean filter(Apple apple) {
                return "yellow".equals(apple.getColor());
            }
        });
        System.out.println(apple1);

写到这里我们可以发现,是不是有点像按钮的点击事件了,接口将过滤条件的方法给暴露出来了,其实写到这里,在程序界面上就已经有提示了,提示我们将这段代码换成landba的方式表达

        List<Apple> apple1 = findApple(list, apple2 -> "yellow".equals(apple2.getColor()));
        System.out.println(apple1);

是不是简洁了很多,好了,这只是对一个很简单的引入而已,好戏在后面。今天有点晚了,要洗洗睡了,后面我们尽快更新

猜你喜欢

转载自blog.csdn.net/jeekmary/article/details/87997328