使用其他值或新值扩展ImmutableMap

And*_*ack 13 java guava

很像是如何ImmutableList扩展这样的:

ImmutableList<Long> originalList = ImmutableList.of(1, 2, 3);
ImmutableList<Long> extendedList = Iterables.concat(originalList, ImmutableList.of(4, 5));
Run Code Online (Sandbox Code Playgroud)

如果我有现有地图,我该如何扩展它(或创建一个包含替换值的新副本)?

ImmutableMap<String, Long> oldPrices = ImmutableMap.of("banana", 4, "apple", 7);
ImmutableMap<String, Long> newPrices = … // Increase apple prices, leave others.
                                         //  => { "banana": 4, "apple": 9 }
Run Code Online (Sandbox Code Playgroud)

(让我们不寻求有效的解决方案,因为显然设计不存在这个问题.这个问题反而寻求最惯用的解决方案.)

Mur*_*nik 20

您可以显式创建构建器:

ImmutableMap<String, Long> oldPrices = ImmutableMap.of("banana", 4, "apple", 7);
ImmutableMap<String, Long> newPrices =
    new ImmutableMap.Builder()
    .putAll(oldPrices)
    .put("orange", 9)
    .build();
Run Code Online (Sandbox Code Playgroud)

编辑:
如评论中所述,这将不允许覆盖现有值.这可以通过遍历不同的初始化块Map(例如,a HashMap)来完成.这不过是优雅的,但应该有效:

ImmutableMap<String, Long> oldPrices = ImmutableMap.of("banana", 4, "apple", 7);
ImmutableMap<String, Long> newPrices =
    new ImmutableMap.Builder()
    .putAll(new HashMap<>() {{
        putAll(oldPrices);
        put("orange", 9); // new value
        put("apple", 12); // override an old value
     }})
    .build();
Run Code Online (Sandbox Code Playgroud)

  • 请不要推荐"双支撑初始化".请参阅http://stackoverflow.com/a/9108655/95725和http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/ (5认同)

Nam*_*ter 6

只需复制ImmutableMap到新的HashMap,添加项目,并转换为新的ImmutableMap

ImmutableMap<String, Long> oldPrices = ImmutableMap.of("banana", 4, "apple", 7);
Map<String, Long> copy = new HashMap<>(oldPrices);
copy.put("orange", 9); // add a new entry
copy.put("apple", 12); // replace the value of an existing entry

ImmutableMap<String, Long> newPrices = ImmutableMap.copyOf(copy);
Run Code Online (Sandbox Code Playgroud)