java - 查找要从 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);
但我找不到一种简单的方法来将键和值放在一起
解决方案
但我找不到一种简单的方法来将键和值放在一起
是的,您可以使用entrySet()方法从映射中获取键和值。
然后你可以像这样使用它
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
推荐阅读
- javascript - 如果验证码未成功解析,如何防止发送数据
- java - 为什么在 LinkedList 末尾添加元素比 ArrayList 需要更长的时间?
- swift - Firebase 数据库查询 orderBy + where 在一个函数中
- android - 在 Firebase 中添加值时如何启动另一个活动
- c++ - 为什么去除尾递归是有益的?
- firebase - 如何从项目中导出所有 Firebase 存储桶
- python - 增加 matplotlib 中绘图文本之间的间距
- python - werkzeug.routing.BuildError:无法为端点“auth.Esp_Index”构建 url。您的意思是“auth.login”吗?
- python - udf 解析 pyspark 数据帧中的字符串 json
- elasticsearch - Skywalking 可以使用生命周期策略或索引模板创建 ES 索引吗?