Java HashMap<String,List<String>>() 比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7826299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java HashMap<String,List<String>>() Comparison
提问by Green
I'm wondering the best way to compare these two HashMaps. I want to verify if they are the same, and if not, what is the difference. If it matters, then I'm wondering what the 2nd one has/does not have that the first hashmap does have. I'll need to know if one has a key the other does not, as well as the Value List differences per key. I'm hoping there is a simple way to map this, but not sure. Basic Example:
我想知道比较这两个 HashMap 的最佳方法。我想验证它们是否相同,如果不同,有什么区别。如果这很重要,那么我想知道第一个哈希图具有/没有的第二个具有/没有什么。我需要知道一个键是否有另一个键,以及每个键的值列表差异。我希望有一种简单的方法来映射它,但不确定。基本示例:
HashMap<String, List<String>> hmOne = new HashMap<String, List<String>>();
List<String>l1 = new ArrayList<String>();
l1.add("one");
l1.add("two");
l1.add("three");
l1.add("four");
l1.add("five");
hmOne.put("firstkey", l1);
l1 = new ArrayList<String>();
l1.add("1");
l1.add("2");
l1.add("3");
l1.add("4");
l1.add("5");
hmOne.put("secondkey", l1);
HashMap<String, List<String>> hmTwo = new HashMap<String, List<String>>();
List<String>l2 = new ArrayList<String>();
l2.add("one");
l2.add("two");
l2.add("four");
l2.add("five");
hmTwo.put("firstkey", l2);
l2 = new ArrayList<String>();
l2.add("1");
l2.add("3");
l2.add("4");
l2.add("5");
hmTwo.put("secondkey", l2);
Thanks for any help.
谢谢你的帮助。
回答by Miserable Variable
HashMap.equals
will tell you if they are identical (same keys and values) but the rest you will have to roll yourself.
HashMap.equals
会告诉你它们是否相同(相同的键和值),但其余的你必须自己滚动。
You will need to iterate the keyset()
of one HashMap
, look for it in the keySet()
of the other and if found then compare the values.
您将需要迭代keyset()
其中一个HashMap
,在另一个中查找它keySet()
,如果找到则比较这些值。
Then, you will have to do the reverse, looking for keys in the second that don't exist in the first. You can probably use Set
methods for this.
然后,您将不得不执行相反的操作,在第二个中查找第一个中不存在的键。您可能可以Set
为此使用方法。
回答by Bob Kuhar
You know that Map's .equals() methodwill tell you if two Maps are equal, right?
你知道 Map 的.equals() 方法会告诉你两个 Map 是否相等,对吧?
If they aren't equal, you're going to have to parse them both and figure out the differences on your own.
如果它们不相等,您将不得不解析它们并自己找出差异。
回答by SuperTron
Off the top of my head, you could first use HashMap.equals() to tell if they are different and then get the keySet of each hashmap and compare them:
在我的脑海中,您可以首先使用 HashMap.equals() 来判断它们是否不同,然后获取每个 hashmap 的 keySet 并比较它们:
What is the fastest way to compare two sets in Java?
Then once you've got the differences in keys, you could repeat the process on your value collections.
然后,一旦获得键的差异,就可以对值集合重复该过程。