Java筛选优秀学生:高效实现成绩过滤函数

本篇文章将带你了解如何使用Java实现一个函数,用于筛选出一个班级中成绩优秀的学生,即分数在90到100之间的学生。

函数接口定义

函数原型如下:

public static List<Student> filter(List<Student> students);

其中 students 是用户传入的参数,Student 类定义如下:

class Student {
    public String name;
    public String id;
    public double score;
}

该函数需要返回一个 List,其中包含所有优秀(分数不小于90,但不能超过100)的学生,且顺序与传入的 students 列表相同。

思路

  1. 遍历学生列表。
  2. 检查每个学生的成绩是否在 90 到 100 之间。
  3. 如果成绩满足条件,将该学生加入新的列表中。
  4. 最后返回新的列表。

代码实现

public static List<Student> filter(List<Student> students) {
    List<Student> excellentStudents = new ArrayList<>();
    for (Student student : students) {
        if (student.score >= 90 && student.score <= 100) {
            excellentStudents.add(student);
        }
    }
    return excellentStudents;
}

代码解析

  1. 创建一个新的 ArrayList excellentStudents 用于存储符合条件的学生。
  2. 使用 for 循环遍历 students 列表。
  3. 对于每个学生,使用 if 语句判断其分数是否在 90 到 100 之间。
  4. 如果满足条件,将该学生添加到 excellentStudents 列表中。
  5. 最后返回 excellentStudents 列表。

通过以上代码,我们成功实现了筛选优秀学生的函数。该函数简单易懂,易于维护,并能满足我们的需求。

Java筛选优秀学生:高效实现成绩过滤函数