public class Apple {
public static List<Apple> filterApplesByColor(List<Apple> inventory, String color) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple: inventory){
if ( apple.getColor().equals(color) ) {
result.add(apple);
}
}
return result;
}
public static List<Apple> filterApplesByWeight(List<Apple> inventory, int weight) {
List<Apple> result = new ArrayList<Apple>();
for (Apple apple: inventory){
if ( apple.getWeight() > weight ){
result.add(apple);
}
}
return result;
}
}
@FunctionalInterface
public interface ApplePredicate{
boolean test (Apple apple);
}
public class ProgressDemo {
public static List<Apple> processApple(List<Apple> appleList, ApplePredicate p) {
List<Apple> res = new ArrayList<>();
for (Apple apple : appleList) {
if (p.test(apple)) {
res.add(apple);
}
}
return res;
}
}
实现有 default 方法的接口, 可以重写 default 方法,不重写则默认使用 interface 中的默认方法。 接口有默认方法之后,个人觉得接口和抽象类之间的区别更小了。
public interface DefaultInterface {
void test();
default String getName() {
return "default";
}
}