Java中HashMap是一种用于存储“键”和“值”信息对的数据结构。不同于LinkedHashMap,它不会维持插入元素的顺序。因此,在键或值的基础上排序HashMap是一个很难的面试问题,如果你不知道如何解决的话。下面让我们看看如何解决这个问题。
1.创建一个简单的HashMap,并插入一些键和值。
Map<String,Integer> aMap = new HashMap<String,Integer>();
//adding keys and values
aMap.put("Five", 5);
aMap.put("Seven", 7);
aMap.put("Four", 4);
aMap.put("Eight", 8);
aMap.put("One", 1);
aMap.put("Two", 2);
aMap.put("Three", 3);
2.利用Set entrySet(): 返回Map.Entry对象的视图集,即映像中的关键字/值对
Set<Map.Entry<String,Integer>> mapEntries = aMap.entrySet();
3.从上述mapEntries创建LinkedList。我们将排序这个链表来解决顺序问题
List<Map.Entry<String,Integer>> aList = new LinkedList<Map.Entry<String,Integer>>(mapEntries);
// sorting the List
Collections.sort(aList, new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String, Integer> ele1, Map.Entry<String, Integer> ele2){
return ele1.getValue().compareTo(ele2.getValue());
}
});
4.Collections.sort()是一个内置方法,仅排序值的列表。它在Collections类中重载。这两种个方法是
public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list, Comparator<? super T> c)
5.完整代码:
package cn.edu.ahui;
import java.util.*;
/*
* @author leo
* @data 2017.3.10
*/
public class SortHashMapByValues {
private static void sortMapByValues(Map<String, Integer> aMap){
Set<Map.Entry<String,Integer>> mapEntries = aMap.entrySet();
System.out.println("Values and Keys before sorting ");
for(Map.Entry<String,Integer> entry : mapEntries)
System.out.println(entry.getKey() + " - "+ entry.getValue());
//use LinkedList to sort, because insertion of elements in linked list is faster than ArrayList.
List<Map.Entry<String,Integer>> aList = new LinkedList<Map.Entry<String,Integer>>(mapEntries);
// sorting the List
Collections.sort(aList, new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String, Integer> ele1, Map.Entry<String, Integer> ele2){
return ele1.getValue().compareTo(ele2.getValue());
}
});
// Storing the list into Linked HashMap to preserve the order of insertion.
Map<String,Integer> aMap2 = new LinkedHashMap<String, Integer>();
for(Map.Entry<String,Integer> entry: aList){
aMap2.put(entry.getKey(), entry.getValue());
}
// printing values after sorting of map
System.out.println("Values and Keys after sorting ");
for(Map.Entry<String,Integer> entry : aMap2.entrySet()){
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
public static void main(String[] args){
Map<String,Integer> aMap = new HashMap<String,Integer>();
//adding keys and values
aMap.put("Five", 5);
aMap.put("Seven", 7);
aMap.put("Four", 4);
aMap.put("Eight", 8);
aMap.put("One", 1);
aMap.put("Two", 2);
aMap.put("Three", 3);
sortMapByValues(aMap);
}
}
6.运行结果:
Values and Keys before sorting
Eight - 8
Five - 5
Four - 4
One - 1
Seven - 7
Two - 2
Three - 3
Values and Keys after sorting
One - 1
Two - 2
Three - 3
Four - 4
Five - 5
Seven - 7
Eight - 8