How to compare two maps by their values(如何按值比较两张地图)
问题描述
如何通过值比较两张地图?我有两个包含相等值的地图,并希望通过它们的值来比较它们.这是一个例子:
How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:
Map a = new HashMap();
a.put("foo", "bar"+"bar");
a.put("zoo", "bar"+"bar");
Map b = new HashMap();
b.put(new String("foo"), "bar"+"bar");
b.put(new String("zoo"), "bar"+"bar");
System.out.println("equals: " + a.equals(b)); // obviously false
我应该如何更改代码以获得真实的?
How should I change the code to obtain a true?
推荐答案
您尝试使用连接构造不同的字符串将失败,因为它是在编译时执行的.这两张地图都有一对;每对都有foo"和barbar"作为键/值,都使用相同的字符串引用.
Your attempts to construct different strings using concatenation will fail as it's being performed at compile-time. Both of those maps have a single pair; each pair will have "foo" and "barbar" as the key/value, both using the same string reference.
假设您真的想在不引用键的情况下比较值集,这只是以下情况:
Assuming you really want to compare the sets of values without any reference to keys, it's just a case of:
Set<String> values1 = new HashSet<>(map1.values());
Set<String> values2 = new HashSet<>(map2.values());
boolean equal = values1.equals(values2);
可能将 map1.values()
与 map2.values()
进行比较 - 但也有可能是它们返回的内容将用于相等比较,这不是您想要的.
It's possible that comparing map1.values()
with map2.values()
would work - but it's also possible that the order in which they're returned would be used in the equality comparison, which isn't what you want.
请注意,使用集合有其自身的问题 - 因为上面的代码会将 {"a":"0", "b":"0"} 和 {"c":"0"} 的映射视为相等...毕竟值集是相等的.
Note that using a set has its own problems - because the above code would deem a map of {"a":"0", "b":"0"} and {"c":"0"} to be equal... the value sets are equal, after all.
如果您可以对您想要的内容提供更严格的定义,那么确保我们为您提供正确的答案会更容易.
If you could provide a stricter definition of what you want, it'll be easier to make sure we give you the right answer.
这篇关于如何按值比较两张地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何按值比较两张地图
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01