Java:HashMap按键值排序

  1. HashMap存储每对键和值作为一个Entry
Map<String,Integer> map=new HashMap<String,Integer>();

2.创建一个简单的HashMap,并插入一些键和值。

map.put("张三", 80);
        map.put("李四", 90);
        map.put("王五", 70);

3.从HashMap恢复entry集合,如下所示。

Set<Entry<String,Integer>> array=map.entrySet();

4.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题。我们之所以要使用链表来实现这个目的,是因为在链表中插入元素比数组列表更快。

List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array);

5.通过传递链表和自定义比较器来使用Collections.sort()方法排序链表。

Collections.sort(list,new Comparator<Entry<String,Integer>>(){
            public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){
                return o1.getValue().compareTo(o2.getValue());
            }
        });

6.得到排序后list之后,可以通过LinkedHashmap存储键和值信息对到新的映射中。由于HashMap不保持顺序,因此我们要使用LinkedHashMap。

完整代码如下:

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class sortMapByValues {
    public static void main(String[] args){
        Map<String,Integer> map=new HashMap<String,Integer>();
        map.put("张三", 80);
        map.put("李四", 90);
        map.put("王五", 70);
        System.out.println("排序之前:");
        Set<Entry<String,Integer>> array=map.entrySet();
        for(Entry<String,Integer> temp:array){
            System.out.println(temp.getKey()+" "+temp.getValue());
        }
        List<Entry<String,Integer>> list=new LinkedList<Entry<String,Integer>>(array);
        Collections.sort(list,new Comparator<Entry<String,Integer>>(){
            public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2){
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        System.out.println("排序之前:");
        for(Entry<String,Integer> temp:list){
            System.out.println(temp.getKey()+" "+temp.getValue());
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值