HashMap排序

HashMap本身是不可以排序的,但其子类LinkedHashMap是有序的,所以我这里演示的是利用LinkedHashMap+List+Collections工具实现HashMap排序

/**
     * HashMap排序
     */
    @Test
    public void testSortHashMap(){
    	//准备数据
        HashMap<Integer, Person> hashMap = new HashMap<>();
        hashMap.put(1,new Person("张三"));
        hashMap.put(5,new Person("李四"));
        hashMap.put(4,new Person("王五"));
        hashMap.put(6,new Person("赵六"));
        hashMap.put(2,new Person("田七"));
        hashMap.put(3,new Person("王八"));

		//排序
        HashMap<Integer, Person> sortHashMap = sortHashMap(hashMap);

		//遍历取出结果
        for (Map.Entry<Integer, Person> entry : sortHashMap.entrySet()) {
            System.out.println(entry.getKey()+"---"+entry.getValue());
        }
    }

	//进行排序的主要内容
    public HashMap<Integer,Person> sortHashMap(HashMap<Integer,Person> hashMap){
        //获取所有键值对
        Set<Map.Entry<Integer, Person>> entrySet = hashMap.entrySet();
        //创建一个List用于排序
        List<Map.Entry<Integer, Person>> list = new ArrayList<Map.Entry<Integer, Person>>(entrySet);
        //排序
        Collections.sort(list, new Comparator<Map.Entry<Integer, Person>>() {
            //小于等于大于分别为负零正
            @Override
            public int compare(Map.Entry<Integer, Person> o1, Map.Entry<Integer, Person> o2) {
                //倒叙
                return o2.getKey() - o1.getKey();
            }
        });
        //创建一个linkedhashmap用于存储排序后的map
        LinkedHashMap<Integer, Person> linkedHashMap = new LinkedHashMap<>();
        //遍历list取出
        for (Map.Entry<Integer, Person> entry : list) {
            linkedHashMap.put(entry.getKey(),entry.getValue());
        }
        //返回数据
        return linkedHashMap;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值