如何将Java hashMap 上的所有内容一一替换为另一内容,但不替换现有的键和值?

发布于 2024-12-01 13:39:00 字数 239 浏览 1 评论 0 原文

我需要将一个 A HashMap 中的所有键和值复制到另一个 B 上,但不替换现有的键和值。

最好的方法是什么?

我在想,而不是迭代 keySet 并检查它是否存在,我会

Map temp = new HashMap(); // generic later
temp.putAll(Amap);
A.clear();
A.putAll(Bmap);
A.putAll(temp);

I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.

Whats the best way to do that?

I was thinking instead iterating the keySet and checkig if it exist or not, I would

Map temp = new HashMap(); // generic later
temp.putAll(Amap);
A.clear();
A.putAll(Bmap);
A.putAll(temp);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

小ぇ时光︴ 2024-12-08 13:39:01

看来您愿意创建一个临时 Map,所以我会这样做:

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

这里,patch 是您要添加到 的地图目标地图。

感谢 Louis Wasserman,这是一个利用 Java 8 中新方法的版本:

patch.forEach(target::putIfAbsent);

It looks like you are willing to create a temporary Map, so I'd do it like this:

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

Here, patch is the map that you are adding to the target map.

Thanks to Louis Wasserman, here's a version that takes advantage of the new methods in Java 8:

patch.forEach(target::putIfAbsent);
方觉久 2024-12-08 13:39:01

使用 GuavaMaps 类的实用方法来计算 2 个地图的差异,您可以在单个地图中完成线,有方法签名可以让您更清楚地了解您想要完成的任务:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}

Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}
橘寄 2024-12-08 13:39:01

只需迭代并添加:

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

编辑添加:

如果您可以对 a 进行更改,您也可以这样做:

a.putAll(b)

并且 a 将完全满足您的需要。 (b 中的所有条目以及 a 中不在 b 中的所有条目)

Just iterate and add:

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

Edit to add:

If you can make changes to a, you can also do:

a.putAll(b)

and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

GRAY°灰色天空 2024-12-08 13:39:01

如果您在 @erickson 的解决方案中更改地图顺序,则只需 1 行即可完成:

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

在这种情况下,您可以将 mapWithNotSoImportantValues 中的值替换为具有相同键的 mapWithImportantValues 中的值。

You can make it in just 1 line if you change maps order in @erickson's solution:

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

In this case you replace values in mapWithNotSoImportantValues with value from mapWithImportantValues with the same keys.

你又不是我 2024-12-08 13:39:01

使用 Map#merge 的 Java 8 解决方案

您可以使用 Map#merge(K key, V value, BiFunction remappingFunction) 使用 remappingFunction< 将值合并到 Map 中/code> 如果已在您想要将其放入的 Map 中找到该密钥。

// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
    map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}

该代码迭代 newMap 条目(keyvalue),并通过方法 map 将每个条目合并到 map 中。代码>合并remappingFunction 在重复键的情况下被触发,在这种情况下,它表示将使用以前的(原始)oldValue 值而不是重写。

使用此解决方案,您不需要临时地图


让我们举一个例子,将 newMap 条目合并到 map 中,并保留原始值以防出现重复的 antry。

Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE");                         // this will NOT be merged into
newMap.put(4, "four");                               // this WILL be merged into
newMap.put(5, "five");                               // this WILL be merged into

Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));

map.forEach((k, v) -> System.out.println(k + " " + v));

<前><代码>1一
2 两个
3 三
4 四
5 五

Java 8 solution using Map#merge

As of you can use Map#merge(K key, V value, BiFunction remappingFunction) which merges a value into the Map using remappingFunction in case the key is already found in the Map you want to put the pair into.

// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
    map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}

The code iterates the newMap entries (key and value) and each one is merged into map through the method merge. The remappingFunction is triggered in case of duplicated key and in that case it says that the former (original) oldValue value will be used and not rewritten.

With this solution, you don't need a temporary Map.


Let's have an example of merging newMap entries into map and keeping the original values in case of the duplicated antry.

Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE");                         // this will NOT be merged into
newMap.put(4, "four");                               // this WILL be merged into
newMap.put(5, "five");                               // this WILL be merged into

Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));

map.forEach((k, v) -> System.out.println(k + " " + v));
1 one
2 two
3 three
4 four
5 five
别在捏我脸啦 2024-12-08 13:39:01
public class MyMap {

public static void main(String[] args) {

    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("key1", "value1");
    map1.put("key2", "value2");
    map1.put("key3", "value3");
    map1.put(null, null);

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("key4", "value4");
    map2.put("key5", "value5");
    map2.put("key6", "value6");
    map2.put("key3", "replaced-value-of-key3-in-map2");
    // used only if map1 can be changes/updates with the same keys present in map2.
    map1.putAll(map2);

    // use below if you are not supposed to modify the map1.
    for (Map.Entry e : map2.entrySet())
        if (!map1.containsKey(e.getKey()))
            map1.put(e.getKey().toString(), e.getValue().toString());
    System.out.println(map1);
}}
public class MyMap {

public static void main(String[] args) {

    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("key1", "value1");
    map1.put("key2", "value2");
    map1.put("key3", "value3");
    map1.put(null, null);

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("key4", "value4");
    map2.put("key5", "value5");
    map2.put("key6", "value6");
    map2.put("key3", "replaced-value-of-key3-in-map2");
    // used only if map1 can be changes/updates with the same keys present in map2.
    map1.putAll(map2);

    // use below if you are not supposed to modify the map1.
    for (Map.Entry e : map2.entrySet())
        if (!map1.containsKey(e.getKey()))
            map1.put(e.getKey().toString(), e.getValue().toString());
    System.out.println(map1);
}}
混浊又暗下来 2024-12-08 13:39:01

Java 8 有这个 API 方法可以满足您的要求。

map.putIfAbsent(key, value)

如果指定的键尚未与值关联(或映射为 null),则将其与给定值关联并返回 null,否则返回当前值。

With Java 8 there is this API method to accomplish your requirement.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

忆梦 2024-12-08 13:39:01

正如其他人所说,您可以使用 putIfAbsent。迭代映射中要插入的每个条目,并在原始映射上调用此方法:

mapToInsert.forEach(originalMap::putIfAbsent);

As others have said, you can use putIfAbsent. Iterate over each entry in the map that you want to insert, and invoke this method on the original map:

mapToInsert.forEach(originalMap::putIfAbsent);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文