/**
* /*
* 练习二:
* 学生对象(姓名,年龄)都有自己的归属地,既然有对应关系。
* 将学生对象和归属地存储到map集合中。
* 注意:同姓名同年龄视为重复的键。
按照学生的年龄进行从小到大的排序。
* 如果要对学生按照姓名排序呢?
*/
public class Practise2 {
public static void main(String[] args) {
/*创建Map集合*/
Map<Student,String> classMap = new HashMap<Student,String>();
classMap.put(new Student("小明",15), "上海");
classMap.put(new Student("小李",15), "沈阳");
classMap.put(new Student("小徐",13), "武汉");
classMap.put(new Student("小明",15), "上海"); //视为重复的键
classMap.put(new Student("天天",14), "武汉");
classMap.put(new Student("刚刚",12), "河北");
/*排序,想到treeSet,比较简单,按姓名排序,按年龄为自然排序*/
Map<Student,String> classTreeMap = new TreeMap<Student,String>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int temp = o1.getName().compareTo(o2.getName());
return temp==0?o1.compareTo(o2):temp;
}
});
classTreeMap.put(new Student("小明",15), "上海");
classTreeMap.put(new Student("小李",15), "沈阳");
classTreeMap.put(new Student("小徐",13), "武汉");
classTreeMap.put(new Student("小明",15), "上海"); //视为重复的键
classTreeMap.put(new Student("天天",14), "武汉");
classTreeMap.put(new Student("刚刚",12), "河北");
for(Student stu : classTreeMap.keySet()){
System.out.println(stu);
}
/*Map转成List的办法*/
List<Map.Entry<Student, String>> list = new ArrayList<Map.Entry<Student, String>>(classTreeMap.entrySet());
for(Entry ent: list){
System.out.println(ent.getKey());
System.out.println(ent.getValue());
}
}
}