Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3597455
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Java

2021-02-04 16:38:36

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;

    }}

阅读(1710) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~