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

2019-07-09  本文已影响0人  昱弟丶

1.按插入顺序排序 LinkedHashMap

Map<String, String> map = new LinkedHashMap<String, String>();
        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<String, String> map = new HashMap<String, String>();
        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<Map.Entry<String, String>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> 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<String, String> map = new TreeMap<String, String>();
        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<String, String> 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
上一篇下一篇

猜你喜欢

热点阅读