有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在映射中交换值

有两种地图:主地图和修改后的地图

if modifiedmap.key == mastermap.key
then set mastermap.value = modifiedmap.value

这就是我们现在正在做的事情

for (Map.Entry<String, String> entry : modified_map.entrySet()) 
{
    for(Map.Entry<String,String> entry1:master_map.entrySet())
    {
        if(entry.getKey().equalsIgnoreCase(entry1.getKey()))
        {
            entry1.setValue(entry.getValue());
        }
    }
}

我使用两个嵌套循环。 地图上有一个名为containsKey()的方法 所以我尝试使用master_map.containsKey()modified_map)然后赋值

但是,我不知道如何在尝试使用单个循环时获取与匹配键对应的mastermap

像这样的

for (Map.Entry<String, String> entry : modified_map.entrySet()) 
{
    if(master_map.containsKey(entry.getKey()))
    then get the corresponding value then swap it
}

共 (1) 个答案

  1. # 1 楼答案

    如果我理解正确,你需要这样的东西:

    for (Map.Entry<String, String> entry : modified_map.entrySet()) {
      if (master_map.containsKey(entry.getKey())
        master_map.put (entry.getKey(),entry.getValue());
    }
    

    这将修改master_map中每个条目的值,该条目的键出现在modified_map

    V put(K key, V value)

    Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)