TreeMap的排序功能,构造方法

/**
 *    /*
         * 练习二:
         * 学生对象(姓名,年龄)都有自己的归属地,既然有对应关系。
         * 将学生对象和归属地存储到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());
        }
    }
}

 

转载于:https://www.cnblogs.com/zyjcxc/p/5463632.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值