package com.hubstc.student;
/*包含学生信息的类*/
public class Student {
private String name;
private int id;
private int age;
private int score;
public Student() {
}
public Student(int id, String name, int age, int score) {
super();
this.name = name;
this.id = id;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 void printRead() {
System.out.println("姓名:"+name + "学号:"+id +"年龄:"+ age+ "成绩:"+score);
}
}
package com.hubstc.student; /*实现map函数的主函数*/
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class StdentApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s1 = new Student(1001, "Alice", 20, 90);
Student s2 = new Student(1002, "Bob", 22, 85);
Student s3 = new Student(1003, "Charlie", 21, 80);
Student s4 = new Student(1004, "David", 19, 95);
Student s5 = new Student(1005, "Eva", 20, 85);
Student s6 = new Student(1006, "Frank", 22, 80);
Student s7 = new Student(1007, "Grace", 21, 90);
Student s8 = new Student(1008, "Henry", 19, 95);
ArrayList<Student> ts = new ArrayList<>();
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);
ts.add(s8);
Map<Integer, Integer> map = new HashMap<>();
for (Student student : ts) {
if(map.get(student.getAge())==null) {
map.put(student.getAge(),1);
}
else {
int flag=map.get(student.getAge());
map.put(student.getAge(),flag+1);
}
}
Set<Integer> set =map.keySet();
for (Integer age: set) {
System.out.println(age+":"+map.get(age));
}
}
}