HashMap本身是不可以排序的,但其子类LinkedHashMap是有序的,所以我这里演示的是利用LinkedHashMap+List+Collections工具实现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<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<Integer, Person> linkedHashMap = new LinkedHashMap<>();
for (Map.Entry<Integer, Person> entry : list) {
linkedHashMap.put(entry.getKey(),entry.getValue());
}
return linkedHashMap;
}