public class Student { private String name; private int age; private double score;}public class Main { public static void main(String[] args) { List students = Arrays.asList(new Student("张三", 18, 89.5), new Student("李四", 20, 60), new Student("王五", 19, 100), new Student("赵六", 22, 89)); // 过滤出年龄大于等于20的学生 List stus1 = filterStudentByAge(students); System.out.println(stus1); // 过滤出成绩大于80的学生 List stus2 = filterStudentByScore(students); System.out.println(stus2); } // 过滤出年龄大于等于20的学生 private static List filterStudentByAge(List students) { List stus = new ArrayList(); for (Student stu : students) { if (stu.getAge() >= 20) { stus.add(stu); } } return stus; } // 过滤出成绩大于80的学生 private static List filterStudentByScore(List students) { List stus = new ArrayList(); for (Student stu : students) { if (stu.getScore() > 80) { stus.add(stu); } } return stus; }}按上面的方式,如果要按另外一个条件过滤呢,又要写一个方法。那可以用策略模式处理,编写一个抽象策略接口,然后编写多个不同策略类实现它。// 策略接口public interface MyPredicate { boolean test(T t);}// 过滤出年龄大于等于20的学生public class filterStudentByAge implements MyPredicate { @Override public boolean test(Student t) { return t.getAge() >= 20; }}// 过滤出成绩大于80的学生public class filterStudentByScore implements MyPredicate { @Override public boolean test(Student t) { return t.getScore() > 80; }}public class Main { public static void main(String[] args) { List students = Arrays.asList(new Student("张三", 18, 89.5), new Student("李四", 20, 60)跟单网, new Student("王五", 19, 100), new Student("赵六", 22, 89)); // 过滤出年龄大于等于20的学生 List stus1 = filterStudent(students, new FilterStudentByAge()); System.out.println(stus1); // 过滤出成绩大于80的学生 List stus2 = filterStudent(students, new FilterStudentByScore()); System.out.println(stus2); } // 按myPredicate策略过滤出满足条件的学生 private static List filterStudent(List students, MyPredicate myPredicate) { List stus = new ArrayList(); for (Student stu : students) { if (myPredicate.test(stu)) { stus.add(stu); } } return stus; }} 02-05 04:01