如何对HashMap按键值排序

如题所述

Java中HashMap是一种用于存储“键”和“值”信息对的数据结构。不同于Array、ArrayList和LinkedLists,它不会维持插入元素的顺序。
1. HashMap存储每对键和值作为一个Entry<K,V>对象。例如,给出一个HashMap,

[html] view plain copy print?
Map<String,Integer> aMap = new HashMap<String,Integer>();
键的每次插入,都会有值对应到散列映射上,生成一个Entry <K,V>对象。通过使用这个Entry <K,V>对象,我们可以根据值来排序HashMap。

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

[java] view plain copy print?
Map<String,Integer> aMap = new HashMap<String,Integer>();

// adding keys and values
aMap.put("Five", 5);
aMap.put("Seven", 7);
aMap.put("Eight", 8);
aMap.put("One",1);
aMap.put("Two",2);
aMap.put("Three", 3);

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

[html] view plain copy print?
Set<Entry<String,Integer>> mapEntries = aMap.entrySet();

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

[java] view plain copy print?
List<Entry<String,Integer>> aList = new LinkedList<Entry<String,Integer>>(mapEntries);

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

[java] view plain copy print?
Collections.sort(aList, new Comparator<Entry<String,Integer>>() {

@Override

public int compare(Entry<String, Integer> ele1,

Entry<String, Integer> ele2) {

return ele1.getValue().compareTo(ele2.getValue());

}

});
温馨提示:答案为网友推荐,仅供参考
相似回答