如何按值比较两张地图

2022-01-25 00:00:00 dictionary compare collections equals java

如何通过值比较两张地图?我有两个包含相等值的地图,并希望通过它们的值来比较它们.这是一个例子:

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.

相关文章