0
点赞
收藏
分享

微信扫一扫

用于缓存一些固定名称的小组件

眼君 2023-12-04 阅读 22

背景

Map<String, Integer> unsortedMap = new HashMap<>();  
unsortedMap.put("One", 1);  
unsortedMap.put("Two", 2);  
unsortedMap.put("Three", 3);  
unsortedMap.put("Four", 4);  

一、关于排序

  1. TreeMap:默认按照key排序
  2. 按照value排序,可使用如下代码
    public static Map<String, Integer> sortEnemyMap(Map<String, Integer> unsortedMap){
        List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());

        // Sort the list based on values
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            	//由大到小
                return (o2.getValue()).compareTo(o1.getValue());
                //由小到大
                //return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        // Convert list to map again
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        return sortedMap;
    }

二、关于转换

  1. HashMap转TreeMap
Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
  1. HashMap转LinkedList
List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());  

举报

相关推荐

0 条评论