一、实现的思想
- 将HashMap中的元素按照Entry<Key,Value>类型存入到LinkedList集合中。
- 实现自定义排序,对LinkedList集合排序。
- LinkedList集合的元素存入到HashMap中,返回排序好的结果
二、代码实现
/**
*
* @param map HashMap<String, Integer> 按照值进行排序
* @return:返回排序后的Map
*/
public static HashMap<String, Integer> hashMapSort(HashMap<String, Integer> map){
//1、按顺序保存map中的元素,使用LinkedList类型
List<Entry<String, Integer>> keyList = new LinkedList<Entry<String, Integer>>(map.entrySet());
//2、按照自定义的规则排序
Collections.sort(keyList, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
if(o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else if(o2.getValue().compareTo(o1.getValue())<0){
return -1;
} else {
return 0;
}
}
});
//3、将LinkedList按照排序好的结果,存入到HashMap中
HashMap<String,Integer> result=new LinkedHashMap<>();
for(Entry<String, Integer> entry:keyList){
result.put(entry.getKey(),entry.getValue());
}
return result;
}