演示Lambdas,以过滤苹果为例
1 | List<Apple> inventory = Arrays.asList(new Apple(80,"green"), |
原始代码
1 | public static List<Apple> filterGreenApples(List<Apple> inventory){ |
演进代码
定义一个接口
1 | interface ApplePredicate { |
接口作为一个参数传递方法
1 | public static List<Apple> filter(List<Apple> inventory, ApplePredicate p) { |
- 方式1
接口的实现,过滤green苹果
1 | public class AppleColorPredicate implements ApplePredicate { |
调用过滤方法
1 | List<Apple> greenApples = filter(inventory, new AppleColorPredicate()); |
- 方式2
匿名类
1 | List<Apple> redApples = filter(inventory, new ApplePredicate() { |
等同于: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") );