Java8新特性——Lambda表达式-1

一、抛出需求

  超市中挑选苹果,挑选条件多样化。

  示例:找出绿色并且重量等于150的苹果,找出红色并且重量小于120苹果。

1、苹果类

public class Apple {

    private String color;
    private int weight;

    public Apple(String color, int weight) {
        this.color = color;
        this.weight = weight;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "color=" + this.color + ",weight=" + this.weight;
    }
}

二、实现方案

  采用策略模式,实现数据筛选。

1、查找苹果类

public class FindApple {

    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;
    }
}

2、实现方法

  • 方法一、继承扩展接口实现多个filter

    • 绿色并且重量等于150的苹果filter
public class GreenAnd150WeightFilter implements AppleFilter{

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

}
    • 红色并且重量小于120苹果 filter
public class RedLess120WeightFilter implements AppleFilter {
    
    @Override
    public boolean filter(Apple apple) {
        return ("red".equals(apple.getColor()) && 120 > apple.getWeight());
    }
}
    • 查询实现与结果
public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(new Apple("green", 150), new Apple("red",100));
List
<Apple> greenApples = findApple(appleList, new GreenAnd150WeightFilter()); System.out.println(greenApples); List<Apple> redApples = findApple(appleList, new RedLess120WeightFilter()); System.out.println(redApples); }

  •  方法二、匿名内部类

public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(new Apple("green", 150), new Apple("red",100));

        //查找绿色并且重量等于150的苹果
        List<Apple> greenApples = findApple(appleList, new AppleFilter() {
            @Override
            public boolean filter(Apple apple) {
                return ("green".equals(apple.getColor()) && 150 == apple.getWeight());
            }
        });
        System.out.println(greenApples);
        //查找红色并且重量小于120苹果 
        List<Apple> redApples = findApple(appleList, new AppleFilter() {    
            @Override
            public boolean filter(Apple apple) {
                return ("red".equals(apple.getColor()) && 120 > apple.getWeight());
            }
        });
        System.out.println(redApples);
    }

 3、小结

  策略模式的两种实现方法,继承实现多个filter类、匿名内部类,可以方便实现复杂条件的数据筛选,但是在代码上显得有些累赘。

  

猜你喜欢

转载自www.cnblogs.com/gavincoder/p/11788024.html