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.
这篇关于如何按值比较两张地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何按值比较两张地图
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01