Lambda(一)lambda表达式初体验

Lambda引入 :

随着需求的不断改变,代码也需要随之变化

需求一:有一个农场主要从一堆苹果中挑选出绿色的苹果

解决方案:常规做法,source code如下

public static void main(String[] args){
List<Apple> apples = Arrays.asList(
new Apple("green", 120),
new Apple("red", 150),
new Apple("green", 170),
new Apple("green", 150),
new Apple("yellow", 100)); List<Apple> filterApple = filterGreenApple(apples);
System.out.println(filterApple);
} public static List<Apple> filterGreenApple(List<Apple> apples){
List<Apple> list = new ArrayList<>();
for(Apple a: apples){
if(a.getColor().equals("green")){
list.add(a);
}
}
return list;
}

假如现在需求发生改变:需要挑选红色、黄色等其他颜色

解决方案:基于上面解决方案,多加一个color参数,source code如下

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

为了应对更复杂的需求,这里我们使用策略模式,source code如下

@FunctionalInterface
public interface FindApple{
boolean filter(Apple apple);
} public static List<Apple> findApple(List<Apple> apples,FindApple findApple){
List<Apple> list = new ArrayList<>();
for(Apple apple:apples){
if(findApple.filter(apple)){
list.add(apple);
}
}
return list;
} public static void main(String[] args){
//匿名类
List<Apple> yellowApple = findApple(apples, new FindApple() {
@Override
public boolean filter(Apple apple) {
return apple.getColor().equals("yellow") && apple.getWeight() >= 100;
}
});
System.out.println(yellowApple); List<Apple> complexApple = findApple(apples, new greenAndGreater150WeightApple ());
System.out.println(complexApple);
} //过滤绿色且重量大于150g的Apple
public static class greenAndGreater150WeightApple implements FindApple{
@Override
public boolean filter(Apple apple) {
return apple.getColor().equals("green")&&apple.getWeight()>=150;
}
}

匿名类的方式比较臃肿,容易发生混淆,故这里引入Lambda表达式,source code如下

//基于上面的source code
List<Apple> lambdaresult = findApple(apples, apple -> apple.getColor().equals("green"));
System.out.println(lambdaresult);
05-16 12:47