【发布时间】:2018-06-26 09:40:28
【问题描述】:
我有两个哈希图:
Map<String, String> mapA = new HashMap<String, String>();
Map<String, String> mapB = new HashMap<String, String>();
TreeSet<String> uniquekeys = new TreeSet<String>();
mapA.put("1","value1");
mapA.put("2","value2");
mapA.put("3","value3");
mapA.put("4","value4");
mapA.put("5","value5");
mapA.put("6","value6");
mapA.put("7","value7");
mapA.put("8","value8");
mapA.put("9","value9");
mapB.put("1","value1");
mapB.put("2","value2");
mapB.put("3","value3");
mapB.put("4","value4");
mapB.put("5","value5");
为了从两个 hashmap 中获取公共键值对,我编写了以下逻辑:
uniquekeys.addAll(mapA.keySet());
uniquekeys.addAll(mapB.keySet());
然后使用treeset: uniquekeys 中的键从mapA 和mapB 中检索唯一键值对。
但这并没有给我 mapA 中所有键的详细信息。我知道这种方式有缺陷,但我无法提出正确的逻辑。
谁能告诉我如何将 mapA 和 mapB 中常见的键值对检索到新的 HashMap 中?
【问题讨论】:
-
新 Map 包含哪些公共键? mapA 的值还是 mapB 的值?还是应该只包含两个 Map 中具有相同键值的键值对?
-
新地图应该包含在mapA和mapB中通用的键值对。
-
@Sidhartha 你试过retainAll吗?
-
您介意使用外部库吗? Google Guava 提供了比较集合的工具:google.github.io/guava/releases/21.0/api/docs/com/google/common/…
标签: java