java-HashMap、TreeMap、LinkedHashMap、ArrayList、LinkedList使用笔记

背景

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());  

你可能感兴趣的:(java,java,笔记,python)