HashMap, LinkedMap, TreeMap -- Java

总结:TreeMap有顺序,HashMap无顺序,LinkedHashMap的顺序与插入顺序相同

HashMap

Map map = new HashMap<>();

        int value = map.get(key);
        int value = map.getOrDefault(key, default);
        map.put(key, value);
        map.size();
        map.containsKey(key);
        map.containsValue(value);
        // travarse
        for(Map.Entry entry: map.entrySet() {
            entry.getKey();
            entry.getValue();
        }
        // get key set
        map.keySet();
        // get value set
        map.values();
        
        map.remove(key);
        map.remove(key, value);
        map.putAll(anotherMap);

LinkedMap

元素的排列顺序与插入顺序相同

Map map = new LinkedHashMap<>();
        map.put("a","b");
        map.put("c","d");
        map.put("e","f");
        for (Map.Entry entry: map.entrySet()) {
            System.out.println(entry.getKey());
        }
        // a, c, e

TreeMap

map中的elememts是按照一定顺序排列的,可以通过自定义comparator来确定排列顺序。

Map map = new TreeMap<>();
        // initialize a TreeMap with comparator

        Map map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[1] < o2[1]) {
                    return -1;
                }
                return 1;
            }
        });
        int[] a1 = {1,2};
        int[] a2 = {1,6};
        int[] a3 = {1,3};
        map.put(a1,1);
        map.put(a2,2);
        map.put(a3,3);
        Set set = map.keySet(); // [1,2], [1,3], [1,6]
        System.out.println(((TreeMap) map).firstKey());
        //  can traver TreeMap the same with HashMap

你可能感兴趣的:(HashMap, LinkedMap, TreeMap -- Java)