我有两个 map ,我需要检查它们是否具有相同的键和相同数量的键并返回一个 boolean 值。我想为此使用流,我得到的是创建另一个列表
mapA
.entrySet()
.stream()
.filter(entry -> mapB.containsKey(entry.getKey()))
.collect(
Collectors.toMap(Entry::getKey, Entry::getValue));
但我的问题是,我可以在一行中完成它,它不会创建另一个列表,而是返回一个 boolean 值,无论它们是否相同。
最佳答案
不需要为此使用流。只需获取 map 的 key 集并使用 equals
, which is specified in Set
as follows :
Returns
true
if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set [.]
Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 10);
m1.put("b", 10);
m1.put("c", 10);
Map<String, Integer> m2 = new HashMap<>();
m2.put("c", 20);
m2.put("b", 20);
m2.put("a", 20);
System.out.println(m1.keySet().equals(m2.keySet())); //true
关于java - 比较两个映射的键并返回 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345658/