模拟使用map进行学生信息(学号、姓名、性别、年龄、专业)存储,key值是学生的学号,value值是对应学生的信息,要求此map中保存的数据根据学号自动升序排序。
package com.zut.Nove;
import java.util.*;
public class MapStudent {
int no;
String name;
String sex;
int age;
String profession;
public MapStudent(int no, String name, String sex, int age, String profession) {
this.no = no;
this.name = name;
this.sex = sex;
this.age = age;
this.profession = profession;
}
@Override
public String toString() {
return "MapStudent{" +
"no=" + no +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", profession='" + profession + '\'' +
'}';
}
public static void main(String[] args) {
MapStudent stu1=new MapStudent(18,"张三","男",18,"数学");
MapStudent stu2=new MapStudent(20,"李四","女",20,"语文");
MapStudent stu3=new MapStudent(8,"王五","男",30,"英语");
Map<Integer,MapStudent>map=new HashMap<Integer,MapStudent>();
map.put(1,stu1);
map.put(2,stu2);
map.put(3,stu3);
//遍历循环输出map中的数据
map.forEach((integer, mapStudent) -> System.out.println(integer+" "+mapStudent));
System.out.println("根据学号自动升序排序");
//List中不可直接写List <Map<Integer,MapStudent>>list=new <Map<Integer,MapStudent>> LinkedList();需要用entrySet方法
List <Map.Entry<Integer,MapStudent>>list=new<Map.Entry<Integer,MapStudent>>LinkedList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, MapStudent>>() {
@Override
public int compare(Map.Entry<Integer, MapStudent> o1, Map.Entry<Integer, MapStudent> o2) {
return o1.getValue().no-o2.getValue().no;
}
});
//遍历输出数据
list.forEach(integerMapStudentEntry -> System.out.println(integerMapStudentEntry));
}
}