需求
- 学校cac有两个考场
- 每个考场有相应的座位号分别对应相应的学生
- 打印出相应信息
- 从中展现Map自定义排序的功能
基本思路
1,假设有两个考场,每个考场的学生有对应的座位号
2,利用两个映射关系完成: (1)考场名字-->考场座位号表 (2)学生映射相应的座位号
PS:其实应该座位号映射到学生才符合我们日常逻辑,不过这里为了体现排序取反了
代码
package 集合框架;
import java.util.*;
/* * 学校cac有两个考场 * 每个考场有相应的座位号分别对应相应的学生 * 打印出相应信息 * */
class Map集合_Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<String,TreeMap<Student,String>> Tab = new TreeMap<String,TreeMap<Student,String>>(); //默认字典序
TreeMap<Student,String> room1 = new TreeMap<Student,String>(new _MyComparator()); //分数升序
TreeMap<Student,String> room2 = new TreeMap<Student,String>(); //分数降序
Tab.put("number_1", room1);
Tab.put("number_2", room2);
room1.put(new Student("lili" ,80),"03");
room1.put(new Student("lilei",80), "02");
room1.put(new Student("Kruskal",98), "11");
room1.put(new Student("prime",99), "01");
room2.put(new Student("liming" ,80),"03");
room2.put(new Student("huahua",80), "02");
room2.put(new Student("Kruskal",98), "11");
room2.put(new Student("prime",99), "01");
room2.put(new Student("A_prime",99), "04");
System.out.println("考场数:"+Tab.size());
Set< Map.Entry<String ,TreeMap<Student,String>> > set = Tab.entrySet();
Iterator< Map.Entry<String ,TreeMap<Student,String>> > it = set.iterator();
while(it.hasNext()) {
Map.Entry<String, TreeMap<Student,String>> ot = it.next();
Set<Map.Entry<Student,String>> s = ot.getValue().entrySet();
String test_room = ot.getKey();
System.out.println("考场:"+test_room);
System.out.println("姓名\t\t分数\t\t座位号");
Map_show(s.iterator());
}
}
public static void Map_show(Iterator<Map.Entry<Student,String>> it) {
while(it.hasNext()) {
Map.Entry<Student,String> ot = it.next();
Student stu = ot.getKey();
String num = ot.getValue();
System.out.println(stu.getName()+"\t\t"+stu.getScore()+"\t\t"+num);
}
System.out.println();
}
}
class _MyComparator implements Comparator<Student> { //按照成绩优先其次姓名字典序的方式排序
public int compare(Student o1, Student o2) {
int num = new Integer(o2.getScore()).compareTo(new Integer(o1.getScore()));
if(num == 0) {
return o1.getName().compareTo(o2.getName());
}
return num;
}
}
class Student implements Comparable<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 void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int compareTo(Student x) { //按成绩升序、姓名字典序排序
int num = new Integer(this.score).compareTo(new Integer(x.getScore()));
if(num == 0) {
return this.name.compareTo(x.getName());
}
return num;
}
}