美文网首页
【JAVA】Map构造+初始化

【JAVA】Map构造+初始化

作者: 一个好汉 | 来源:发表于2021-09-14 00:03 被阅读0次

    1. 使用静态初始化

    import java.util.HashMap;
    import java.util.Map;
    
    class Scratch {
        private static final Map<String, String> rank = new HashMap<>();
        static
        {
            rank.put("1", "lisa");
            rank.put("2", "John");
        }
        public static void main(String[] args) {
            rank.forEach((key, value)->System.out.printf("key: %s, value: %s\n", key, value));
        }
    }
    

    结果:

    key: 1, value: lisa
    key: 2, value: John

    2. 使用匿名类进行初始化

    import java.util.HashMap;
    import java.util.Map;
    
    class Scratch {
        public static void main(String[] args) {
            Map<String, String > rank = new HashMap<String, String>(){{
               put("1", "lisa");
               put("2", "John");
            }};
            rank.forEach((key, value)->System.out.printf("key: %s, value: %s\n", key, value));
        }
    }
    

    结果:

    key: 1, value: lisa
    key: 2, value: John

    HashMap 此写法虽文艺 但有内存泄露隐患

    3. 使用 Guava 工具类 ImmutableMap 创建

    Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
    //或者
    Map<String, String> test = ImmutableMap.<String, String>builder()
        .put("k1", "v1")
        .put("k2", "v2")
        ...
        .build();
    

    这种方法来自 JAVA构造MAP并初始化MAP
    工程中如有引用到 Guava 使用此方法我觉得是极好的

    相关文章

      网友评论

          本文标题:【JAVA】Map构造+初始化

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