MST
星途 面试题库

面试题:Java中如何利用Map接口对一组学生成绩按分数段进行分组统计

假设有一个List<Student>,Student类包含属性name(姓名)和score(分数)。请使用Java的Map接口,将这些学生按分数段(0 - 59, 60 - 79, 80 - 100)进行分组,并统计每个分数段的学生人数,写出实现代码。
25.3万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.*;

class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

public class StudentGrouping {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
                new Student("Alice", 85),
                new Student("Bob", 58),
                new Student("Charlie", 72),
                new Student("David", 90),
                new Student("Eve", 65)
        );

        Map<String, Integer> scoreGroupCount = new HashMap<>();
        scoreGroupCount.put("0 - 59", 0);
        scoreGroupCount.put("60 - 79", 0);
        scoreGroupCount.put("80 - 100", 0);

        for (Student student : students) {
            if (student.getScore() >= 0 && student.getScore() <= 59) {
                scoreGroupCount.put("0 - 59", scoreGroupCount.get("0 - 59") + 1);
            } else if (student.getScore() >= 60 && student.getScore() <= 79) {
                scoreGroupCount.put("60 - 79", scoreGroupCount.get("60 - 79") + 1);
            } else if (student.getScore() >= 80 && student.getScore() <= 100) {
                scoreGroupCount.put("80 - 100", scoreGroupCount.get("80 - 100") + 1);
            }
        }

        for (Map.Entry<String, Integer> entry : scoreGroupCount.entrySet()) {
            System.out.println(entry.getKey() + " 人数: " + entry.getValue());
        }
    }
}