@Override public String toString(){ return"Apple{" + "color='" + color + '\'' + ", weight=" + weight + '}'; } }
然后准备一个工具类去生成测试代码所需的苹果的集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassAppleUtil{ publicstatic List<Apple> getApples(){ return Arrays.asList( new Apple("green", 100), new Apple("green", 120), new Apple("red", 130), new Apple("green", 140), new Apple("red", 150), new Apple("green", 160), new Apple("green", 170), new Apple("red", 180), new Apple("green", 190), new Apple("red", 200), new Apple("green", 210) ); } }
publicstatic List<Apple> filterRedApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if ("red".equals(apple.getColor())) { result.add(apple); } } return result; }
publicstatic List<Apple> filterApplesByPredicate(List<Apple> inventory, ApplePredicate predicate){ List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if (predicate.test(apple)) { result.add(apple); } } return result; }
测试代码
1 2 3 4 5 6 7
publicstaticvoidmain(String[] args){
List<Apple> apples = filterApplesByPredicate(AppleUtil.getApples(), new AppleGreenColorPredicate()); for (Apple apple : apples) { System.out.println(apple); } }