如何比较两个地图的值 [英] How to compare two maps by their values

查看:104
本文介绍了如何比较两个地图的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    .... what to call to obtain a true?

[[ EDIT:]请修改并修正此问题它实际上是应该的意思。上面的代码打印true,而不是false。 ]]

[[ someone please edit and fix this question to mean whatever it's actually supposed to mean. The code above prints "true", not "false". ]]

显然,为了实现比较并不困难,足以比较所有键及其相关值。我不相信我是第一个这样做,所以必须已经有一个库函数在java或jakarta.commons库之一。

Obviously, to implement a comparison it not difficult, it is enough to compare all keys and their associated values. I don't believe I'm the first one to do this, so there must be already a library functions either in java or in one of the jakarta.commons libraries.

感谢

推荐答案

您尝试使用连接构建不同的字符串将失败,因为它在编译时执行。这两个地图都有一对;每个对都有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.

这篇关于如何比较两个地图的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆