【问题标题】:How to compare two hasmaps in java irrespective of their keys? [duplicate]java - 如何在java中比较两个哈希图而不考虑它们的键? [复制]
【发布时间】:2012-05-30 10:33:38
【问题描述】:

可能重复:
How to compare two hashmaps in java?

您好,我有两个不同的地图,其值如下所示

地图,

1.=============Employee=================


Key : 1_10 : Value : 13/04/2012
Key : 1_11 : Value : 18/04/2012
Key : 1_12 : Value : 19/04/2012
Key : 1_14 : Value : 23/04/2012
Key : 1_13 : Value : 20/04/2012
Key : 1_16 : Value : 25/04/2012
Key : 1_1  : Value : 02/04/2012
Key : 1_15 : Value : 24/04/2012
Key : 1_18 : Value : 27/04/2012
Key : 1_3  : Value : 04/04/2012
Key : 1_17 : Value : 26/04/2012
Key : 1_2  : Value : 03/04/2012
Key : 1_5  : Value : 06/04/2012
Key : 1_19 : Value : 30/04/2012
Key : 1_4  : Value : 05/04/2012
Key : 1_7  : Value : 10/04/2012
Key : 1_6  : Value : 09/04/2012
Key : 1_9  : Value : 12/04/2012
Key : 1_8  : Value : 11/04/2012

2.=============Working day=================

Key : 27 : Value : 27/4/2012
Key : 02 : Value : 02/4/2012
Key : 26 : Value : 26/4/2012
Key : 19 : Value : 19/4/2012
Key : 11 : Value : 11/4/2012
Key : 04 : Value : 04/4/2012
Key : 30 : Value : 30/4/2012
Key : 06 : Value : 06/4/2012
Key : 13 : Value : 13/4/2012
Key : 09 : Value : 09/4/2012
Key : 03 : Value : 03/4/2012
Key : 23 : Value : 23/4/2012
Key : 20 : Value : 20/4/2012
Key : 16 : Value : 16/4/2012
Key : 10 : Value : 10/4/2012
Key : 18 : Value : 18/4/2012
Key : 25 : Value : 25/4/2012
Key : 17 : Value : 17/4/2012
Key : 12 : Value : 12/4/2012
Key : 24 : Value : 24/4/2012
Key : 05 : Value : 05/4/2012

我只想比较这两个哈希映射并给出映射中不存在的值。

【问题讨论】:

  • 这个答案应该有效:stackoverflow.com/a/10813470/1400768
  • 这没有帮助,所以我改变了问题并询问了
  • @Tony 这怎么没有帮助?另外,同样的问题不要问两次。
  • @Tony 您可能会得到相同的答案。你为什么不试着让它工作,如果你不能,回来代码不符合你的期望?
  • 您得到了三个答案,但没有对任何一个发表评论。你只是放弃了这个问题并重新提出。这种行为在这里不仅不受欢迎,实际上还会让人生你的气。

标签: java hashmap


【解决方案1】:

假设 map1 是您的第一个地图的哈希图,而 map2 是您的第二个地图的哈希图。那么,

Collection<String> c1 = map1.values();
c1.removeAll(map2.values());  // this one removes all the values from c1 which are also in map2.
Iterator<String> it = c1.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

因此您会得到 map1 包含而 map2 不包含的值。

【讨论】:

  • 仅仅遍历一个集合就需要很多字符;我们在未来,现在使用 foreach。
  • 除了格式和额外的冗长之外,我没有遇到任何问题。
  • @DaveNewton,@JackAss,上述解决方案没有给出任何例外,但它不会删除 map1 包含哪些 map2 不包含。谢谢你们的努力,我必须解决这个问题,所以我已经问了两次改变问题,以便理解不要让任何人生气。我也知道这是我得到准确答案并与像你们这样的好人建立联系的地方。如果我的问题让你们生气了,我很抱歉。托尼
猜你喜欢
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多