java 使用附加值或新值扩展 ImmutableMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29828829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:59:23  来源:igfitidea点击:

Extending an ImmutableMap with additional or new values

javaguava

提问by Andres Jaan Tack

Much like how an ImmutableListcould be extended as such:

就像如何ImmutableList扩展这样的:

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

If I have an existing map, how could I extend it (or create a new copy with replaced values)?

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

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

(Let's not seek an efficient solution, as apparently that doesn't exist by design. This question rather seeks the most idiomatic solution.)

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

回答by Mureinik

You could explicitly create a builder:

您可以显式创建一个构建器:

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

EDIT:
As noted in the comments, this won't allow overriding existing values. This can be done by going through an initializer block of a different Map(e.g., a HashMap). It's anything but elegant, but it should work:

编辑:
如评论中所述,这将不允许覆盖现有值。这可以通过经过不同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();

回答by NamshubWriter

Just copy the ImmutableMapinto a new HashMap, add the items, and convert to a new ImmutableMap

只需将 复制ImmutableMap到 new 中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);

回答by Bogdan Calmac

Staying with Guava, you can create a utility method that skips duplicates when building the new map. This is done with the help of Maps.filterKeys().

继续使用 Guava,您可以创建一个实用方法,在构建新地图时跳过重复项。这是在 的帮助下完成的Maps.filterKeys()

This is the utility function:

这是效用函数:

private <T, U> ImmutableMap<T, U> extendMap(ImmutableMap<T, U> original, ImmutableMap<T, U> changes) {
    return ImmutableMap.<T, U>builder()
            .putAll(changes)
            .putAll(Maps.filterKeys(original, key -> !changes.containsKey(key)))
            .build();
}

and here is a unit test with your data (based on AssertJ).

这是对您的数据进行的单元测试(基于 AssertJ)。

@Test
public void extendMap() {
    ImmutableMap<String, Integer> oldPrices = ImmutableMap.of("banana", 4, "apple", 7);
    ImmutableMap<String, Integer> changes = ImmutableMap.of("orange", 9, "apple", 12);
    ImmutableMap<String, Integer> newPrices = extendMap(oldPrices, changes);
    assertThat(newPrices).contains(
            entry("banana", 4),
            entry("apple", 12),
            entry("orange", 9));

}

UPDATE: Here is a slightly more elegant alternative for the utility function based on Maps.difference().

更新:这是基于Maps.difference().

private <T, U> ImmutableMap<T, U> extendMap(ImmutableMap<T, U> original, ImmutableMap<T, U> changes) {
    return ImmutableMap.<T, U>builder()
            .putAll(Maps.difference(original, changes).entriesOnlyOnLeft())
            .putAll(changes)
            .build();
}

回答by JustifiedAndAncient

Well I've done this with streams but it isn't perfect:

好吧,我已经用流完成了这个,但它并不完美:

public static <K,V> Map<K,V> update(final Map<K,V> map, final Map.Entry<K,V> replace)
{
    return Stream.concat(
        Stream.of(replace),
        map.entrySet().stream()
            .filter(kv -> ! replace.getKey().equals(kv.getKey()))
    .collect(Collectors.toMap(SimpleImmutableEntry::getKey, SimpleImmutableEntry::getValue));
}

and this only inserts or updates a single entry. Note that ImmutableMap & the associated collector can be dropped in (which is what I actually used)

这只会插入或更新单个条目。请注意,可以删除 ImmutableMap 和相关的收集器(这是我实际使用的)

回答by Android_Rookie

Not a terribly performant code, but the below would work

不是一个非常高效的代码,但下面的代码会起作用

private <K, V> ImmutableMap.Builder<K, V> update(final ImmutableMap.Builder<K, V> builder, final List<ImmutablePair<K, V>> replace) {
    Set<K> keys = replace.stream().map(entry -> entry.getKey()).collect(toSet());
    Map<K, V> map = new HashMap<>();
    builder.build().forEach((key, val) -> {
        if (!keys.contains(key)) {
            map.put(key, val);
        }
    });
    ImmutableMap.Builder<K, V> newBuilder = ImmutableMap.builder();
    newBuilder.putAll(map);
    replace.stream().forEach(kvEntry -> newBuilder.put(kvEntry.getKey(), kvEntry.getValue()));
    return newBuilder;
}