java map 集合 默认的排序和几种遍历方法

1.按插入顺序排序 LinkedHashMap

Map map = new LinkedHashMap();
        map.put("11", "value1");
        map.put("zame", "value2");
        map.put("name", "value3");
        map.put("3", "value4");

        //第一种:普遍使用,二次取值
       System.out.println("通过Map.keySet遍历key和value:");
        for (String key : map.keySet()) {
            System.out.println("key= "+ key + " and value= " + map.get(key));
        }

结果:

通过Map.keySet遍历key和value:
key= 11 and value= value1
key= zame and value= value2
key= name and value= value3
key= 3 and value= value4

2.按key hash值排序 HashMap

Map map = new HashMap();
        map.put("11", "value1");
        map.put("zame", "value2");
        map.put("name", "value3");
        map.put("3", "value4");

      //第二种
        System.out.println("通过Map.entrySet使用iterator遍历key和value:");
        Iterator> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

结果:

通过Map.entrySet使用iterator遍历key和value:
key= 11 and value= value1
key= 3 and value= value4
key= zame and value= value2
key= name and value= value3

3.按key值排序 TreeMap

Map map = new TreeMap();
        map.put("11", "value1");
        map.put("zame", "value2");
        map.put("name", "value3");
        map.put("3", "value4");

         //第三种:推荐,尤其是容量大时
        System.out.println("通过Map.entrySet遍历key和value");
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

结果

通过Map.entrySet遍历key和value
key= 11 and value= value1
key= 3 and value= value4
key= name and value= value3
key= zame and value= value2

你可能感兴趣的:(java map 集合 默认的排序和几种遍历方法)