美文网首页
java map 集合 默认的排序和几种遍历方法

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

作者: 昱弟丶 | 来源:发表于2019-07-09 14:51 被阅读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
    

    相关文章

      网友评论

          本文标题:java map 集合 默认的排序和几种遍历方法

          本文链接:https://www.haomeiwen.com/subject/jspxkctx.html