Map排序问题(有序或者无序)

有时候会在对接参数时会对参数的排序有要求.这里就需要研究Map的排序机制

1.hashMap是无序的

2.treeMap则是有序的

   1).如果不指定排序器则默认按照key来排序:

public static void main(String[] args) {
                Map<Integer, Student> stuMap = new TreeMap<Integer, Student>();
                Student s1 = new Student(20, "小三", 18);
                Student s2 = new Student(10, "小四", 18);
                Student s3 = new Student(12, "小五", 18);
                Student s4 = new Student(51, "小六", 18);
                Student s5 = new Student(1, "小七", 18);
                stuMap.put(s1.getId(), s1);
                stuMap.put(s2.getId(), s2);
                stuMap.put(s3.getId(), s3);
                stuMap.put(s4.getId(), s4);
                stuMap.put(s5.getId(), s5);
                for (Student stu : stuMap.values()) {
                        System.out.println(stu.getId() + " " + stu.getName());
                }
               
        }


输出结果1 小七
      10 小四
      12 小五
      20 小三
      51 小六

 

 

2).如果指定了排序器则按照排序器来排序

    public static void main(String[] args) {  
        //指定排序器  
        TreeMap<String, String> treeMap2 = new TreeMap<String, String>(new Comparator<String>(){  
  
            /* 
             * int compare(Object o1, Object o2) 返回一个基本类型的整型, 
             * 返回负数表示:o1 小于o2, 
             * 返回0 表示:o1和o2相等, 
             * 返回正数表示:o1大于o2。 
             */  
            public int compare(String o1, String o2) {  
              
                //指定排序器按照降序排列  
                return o2.compareTo(o1);  
            }     
        });  
        treeMap2.put("2", "1");  
        treeMap2.put("b", "1");  
        treeMap2.put("1", "1");  
        treeMap2.put("a", "1");  
        System.out.println("treeMap2="+treeMap2);  
    }  

输出结果treeMap2={b=1, a=1, 2=1, 1=1}  

 

转载于:https://my.oschina.net/MrBamboo/blog/731712

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值