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;
}
}
Java8 的代码简化
@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;
}
}