HashMap根据value的值排序,如何实现?
来源:5-3 自定义类型的集合排序
20221206
2023-03-07 17:42:12
HashMap<String, Integer> goodsPriceMap = new HashMap<>()
goodsPriceMap.put("A1", 2);
goodsPriceMap.put("A2", 3);
goodsPriceMap.put("A3", 4);
goodsPriceMap.put("A4", 5);
goodsPriceMap.put("A5", 8);
goodsPriceMap.put("A6", 6);
将goodsPriceMap根据value值从大到小排序,该怎么实现?
可以用Comparator接口比较器吗?
1回答
好帮手慕小尤
2023-03-07
同学你好,同学可以参考下方代码,
import java.util.*;
public class Test {
public static Map<String, Integer> sortMap(Map<String, Integer> map) {
//利用Map的entrySet方法,转化为list进行排序
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
//利用Collections的sort方法对list排序
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
//正序排列,倒序反过来
return o1.getValue() - o2.getValue();
}
});
//遍历排序好的list,一定要放进LinkedHashMap,因为只有LinkedHashMap是根据插入顺序进行存储
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String,Integer> e : entryList) {
linkedHashMap.put(e.getKey(),e.getValue());
}
return linkedHashMap;
}
public static void main(String[] args) {
HashMap<String, Integer> goodsPriceMap = new HashMap<>();
goodsPriceMap.put("A1", 2);
goodsPriceMap.put("A2", 3);
goodsPriceMap.put("A3", 4);
goodsPriceMap.put("A4", 5);
goodsPriceMap.put("A5", 8);
goodsPriceMap.put("A6", 6);
System.out.println(goodsPriceMap);
Map<String, Integer> sortMap = sortMap(goodsPriceMap);
System.out.println(sortMap);
}
}祝学习愉快!
相似问题