lambdas 演进

演示Lambdas,以过滤苹果为例

1
2
3
List<Apple> inventory = Arrays.asList(new Apple(80,"green"),
new Apple(155, "green"),
new Apple(120, "red"));

原始代码

1
2
3
4
5
6
7
8
9
public static List<Apple> (List<Apple> inventory){
List<Apple> result = new ArrayList<>();
for (Apple apple: inventory){
if ("green".equals(apple.getColor())) {
result.add(apple);
}
}
return result;
}

演进代码

定义一个接口

1
2
3
interface ApplePredicate {
boolean test(Apple a);
}

接口作为一个参数传递方法

1
2
3
4
5
6
7
8
9
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p) {
List<Apple> result = new ArrayList<>();
for(Apple apple : inventory){
if(p.test(apple)){
result.add(apple);
}
}
return result;
}
  • 方式1

接口的实现,过滤green苹果

1
2
3
4
5
public class AppleColorPredicate implements ApplePredicate {
public boolean test(Apple apple){
return "green".equals(apple.getColor());
}
}

调用过滤方法

1
List<Apple> greenApples = filter(inventory, new AppleColorPredicate());
  • 方式2

匿名类

1
2
3
4
5
List<Apple> redApples = filter(inventory, new ApplePredicate() {
public boolean test(Apple a){
return a.getColor().equals("red");
}
});

等同于:Java8写法

1
List<Apple> redApples = filter(inventory, a -> a.getColor().equals("red"));

Lambdas

1
static <T> Collection<T> filter(Collection<T> c, Predicate<T> p);

So you wouldn’t even have to write methods like filterApples because, for example, the previous call

filterApples(inventory, (Apple a) -> a.getColor().equals("red") );

could simply be written as a call to the library method filter:

filter(inventory, (Apple a) -> a.getColor().equals("red") );