集合算平均年龄和平均成绩

package com.company;

public class Student {
    private String name;

    private int age;

    private int score;

    private String classNum;

    public Student(String name,int age,int score,String classNum){
        this.name = name;
        this.age = age;
        this.score = score;
        this.classNum = classNum;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getClassNum() {
        return classNum;
    }

    public void setClassNum(String classNum) {
        this.classNum = classNum;
    }
}



package com.company;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Students {
    public static void main(String[] args) {
        Map> ClassNum2Score = new HashMap<>();
        List StudentList = new ArrayList<>();
        StudentList.add(new Student("Tom", 18, 100, "class05"));
        StudentList.add(new Student("Jerry", 22, 70, "class04"));
        StudentList.add(new Student("Owen", 25, 90, "class05"));
        StudentList.add(new Student("Jim", 30,80 , "class05"));
        StudentList.add(new Student("Steve", 28, 66, "class06"));
        StudentList.add(new Student("Kevin", 24, 100, "class04"));
        int total = 0;
        for (Student student : StudentList){
            total += student.getAge();
        }
        System.out.println("学生的平均年龄是:"+total/StudentList.size());

        for (Student student:StudentList){
            if (ClassNum2Score.containsKey(student.getClassNum())){
                List list = ClassNum2Score.get(student.getClassNum());
                list.add(student.getScore());
                ClassNum2Score.put(student.getClassNum(),list);
            }
            else {
                List ScoreList = new ArrayList<>();
                ScoreList.add(student.getScore());
                ClassNum2Score.put(student.getClassNum(),ScoreList);
            }
        }
        int avgscore = 0;
        Map Class2Score = new HashMap<>();
        for (String string :ClassNum2Score.keySet()){
           List list = ClassNum2Score.get(string);
            int classscore = 0;
           for (Integer integer : list){
               classscore += integer;
           }
            avgscore = classscore/list.size();
            Class2Score.put(string,avgscore);
        }
        for (String ss:Class2Score.keySet()){
            System.out.println(ss+"的平均成绩是"+Class2Score.get(ss));
        }
    }
}

你可能感兴趣的:(集合算平均年龄和平均成绩)