首页 > 解决方案 > 查找要从 hashmap1 添加/删除的键和值等于 hashmap2

问题描述

假设我有以下情况:

我想找到要从 hashmap1 中添加/删除的键和值,以便 hashmap1 和 hashmap2 具有相同的值。

hashmap1: {obj2=[Brazil], obj1=[Argentina, Chile, Brazil], obj3Mobile=[Russia]}

hashmap2: {obj3Op=[Germany], obj2=[Brazil, China], obj1=[Argentina, Brazil]}

我的预期输出是:

add:  {obj2=[China], obj3Op=[Germany]}

remove: {obj3Mobile=[Russia], obj1=[Chile]}

为了重现数据集:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

public class Main
{
    public static void main(String[] args) {
        Map<String, List<String>> dictOP = new HashMap<String, List<String>>();
        Map<String, List<String>> dictMobile = new HashMap<String, List<String>>();
        
        List<String> obj1Mobile = new ArrayList<String>();
        List<String> obj2Mobile = new ArrayList<String>();
        List<String> obj3Mobile = new ArrayList<String>();
        
        List<String> obj1Op = new ArrayList<String>();
        List<String> obj2Op = new ArrayList<String>();
        List<String> obj3Op = new ArrayList<String>();
        
        
        obj1Mobile.add("Argentina");
        obj1Mobile.add("Chile");
        obj1Mobile.add("Brazil");
        obj2Mobile.add("Brazil");
        obj3Mobile.add("Russia");
        
        
        obj1Op.add("Argentina");
        obj1Op.add("Brazil");
        obj2Op.add("Brazil");
        obj2Op.add("China");
        obj3Op.add("Germany");
        
        dictOP.put("obj1", obj1Op);
        dictOP.put("obj2", obj2Op);
        dictOP.put("obj3Op", obj3Op);
        
        dictMobile.put("obj1", obj1Mobile);
        dictMobile.put("obj2", obj2Mobile);
        dictMobile.put("obj3Mobile", obj3Mobile);
        
        System.out.println(dictMobile);
        System.out.println(dictOP);
        

    }
}

使用下面的这种方法,我只能找到要添加和删除的键。

    //Union of keys from both maps
    HashSet<String> removeKey = new HashSet<>(dictMobile.keySet());
    removeKey.addAll(dictOP.keySet());
    removeKey.removeAll(dictMobile.keySet());
     
    HashSet<String> addKey = new HashSet<>(dictOP.keySet());
    addKey.addAll(dictMobile.keySet());
    addKey.removeAll(dictOP.keySet());
    
    System.out.println(removeKey);
    System.out.println(addKey);

但我找不到一种简单的方法来将键和值放在一起

标签: javahashmap

解决方案


但我找不到一种简单的方法来将键和值放在一起

是的,您可以使用entrySet()方法从映射中获取键和值。

然后你可以像这样使用它

for (var entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

推荐阅读