传统的方式 new HashMap

HashMap<Object, Object> map = new HashMap<>();
        map.put("name","xiaosheng");

双大括号方式

好处:

  • (1)相对普通的看起来行数更少(不考虑换行等);

  • (2)可读性更高;

  • (3)创建和初始化在同一个表达式里一起完成了。

坏处:

  • (1)并不是一个被广泛知道和使用的方法;

  • (2)每次使用它都会额外产生一个匿名类;

  • (3)不支持泛型推断(List list = new ArrayList<>());

  • (4)不支持final的类;

  • (5)会持有隐式的引用,这可能会导致内存泄露;

原文链接:

// 双大括号初始化
        Map<String, String> map = new HashMap<String, String>() {{
            put("name", "xiaosheng");
            put("sex", "M");
        }};

集合类

这样有一个缺点,创建的Map中只能有这一个元素,不能添加删除修改。

Map<String, String> map = Collections.singletonMap("name", "xiaosheng");

Stream流方式

生成可变Map

    Map<String, String> collect = Stream.of(
    new AbstractMap.SimpleEntry<>("name", "xiaosheng"),
    new AbstractMap.SimpleEntry<>("age", "18"))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

生成不可变Map

map = Stream.of(
        new AbstractMap.SimpleEntry<>("name", "xiaosheng"),
        new AbstractMap.SimpleEntry<>("age", "18"))
        .collect(Collectors.collectingAndThen(
                Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
                Collections::unmodifiableMap

Guava

Map<String, String> collect = ImmutableMap.of("key1", "value1", "key2", "value2");

扩展

java9的话可以直接用Map.of()方式创建Map,更方便。

分类: java

0 条评论

发表评论

Avatar placeholder

您的电子邮箱地址不会被公开。 必填项已用*标注

ICP备案号: 辽ICP备20003309号