之前在第一章中提到了谓词(predicate),第一章超链接,今天继续进行扩展。第一章中找指定重量的苹果或者指定颜色的苹果写了好几个方法,本章将这些方法合并到一个去,毕竟这都是苹果的属性。
先写一个接口:
public interface ApplePredicate {
boolean test (Apple apple);
}
实现接口:找出大于100g的苹果:
public class AppleSelfPredicate implements ApplePredicate{
@Override
public boolean test(Apple apple) {
return apple.getWeight()>100;
}
}
做一下简单的测试。
public static List<Apple> filterApples(List<Apple> inventory,ApplePredicate p) {
List<Apple> result=new ArrayList<>();
for (Apple apple : inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
List<Apple> inventory=Arrays.asList(new Apple(10,"red"),
new Apple(100,"green"),
new Apple(200,"red"));
List<Apple> heavyApples=filterApples(inventory,new AppleSelfPredicate());
System.out.println(heavyApples);
}
如果要查询颜色为红色大于100g的苹果,只需要改变AppleSelfPredicate 类中的test方法即可。
return apple.getWeight()>100 && "red".equals(apple.getColor());
好了。filterApples方法中ApplePredicate p就是行为参数化的用法。当然,匿名类依旧起作用:
List<Apple> redApples=filterApples(inventory, new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return "red".equals(apple.getColor());
}
});
使用Lambda表达式,改进上面的查询方法,这时候需要将List抽象化。
public static <T> List<T> filter(List<T> list,Predicate<T> p){
List<T> result=new ArrayList<>();
for (T t : list) {
if (p.test(t)) {
result.add(t);
}
}
return result;
}
这样就可以直接调用了:
List<Apple> redApples2=filter(inventory, (Apple a) -> "red".equals(a.getColor()));
System.out.println("redApples2:"+redApples2);
List numbers=new ArrayList<>();
for (int j = 0; j < 10; j++) {
numbers.add(j);
}
List<Integer> eventNumbers=filter(numbers, (Integer i) -> i%2 ==0);
System.out.println(eventNumbers);
最后说一下,Lamdba简写Runnable。
Thread t=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hi");
}
});
简写成:
Thread thread=new Thread(() -> System.out.println("hi") );
好了,今天就是这样了。下一章要老老实实地学Lambda表达式了。