在Java 8里写下File::isHidden的时候,你就创建了一个方法引用,你同样可以传递它。
编写把函数作为一等值来传递的程序
public static boolean isGreenApple(Apple apple) {
return "green".equals(apple.getColor());
}
static List<Apple> filterApples(List<Apple> inventory,
Predicate<Apple> 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 = new ArrayList<>();
Apple apple = new Apple();
apple.setColor("green1");
apple.setWeight(10);
inventory.add(apple);
//此处把isGreenApple方法作为参数传入 filterApples在执行test方法时会调用isGreenApple
inventory = filterApples(inventory, AppleMethod::isGreenApple);
System.out.println(inventory.size());
//也可以现场使用lambda定义好需要使用的方法
inventory = filterApples(inventory, (Apple a) ->
"green".equals(apple.getColor()));
System.out.println(inventory.size());
}