我已经初始化了两个哈希映射,如下所示
Map<String,List<String>> propertiesMapList1=new HashMap<String,List<String>>();
Map<String,List<String>> propertiesMapList2=new HashMap<String,List<String>>();
并添加一个包含多个值的键。
propertiesMapList1.put(srvFld, values);
propertiesMapList2.put(srvFld, values);
我能够在两个哈希图中获取公共密钥,我如何获得相应的值?
Set<String> keysInA = new HashSet<String>(propertiesMapList1.keySet());
Set<String> keysInB = new HashSet<String>(propertiesMapList2.keySet());
// Keys in A and not in B
Set<String> inANotB = new HashSet<String>(keysInA);
inANotB.removeAll(keysInB);
// Keys common to both maps
Set<String> commonKeys = new HashSet<String>(keysInA);
commonKeys.retainAll(keysInB);
Iterator itr = commonKeys.iterator();
while(itr.hasNext()){
System.out.println("common key ::" +itr.next());
}
答案 0 :(得分:1)
您可以在根据其中一个密钥集创建新Set.retainAll
后使用Set
,然后获取两个地图的每个密钥。
Map<String,List<String>> map0 =new HashMap<String,List<String>>();
Map<String,List<String>> map1 =new HashMap<String,List<String>>();
map0.put("Foo", Arrays.asList(new String[]{"a", "b", "c"}));
map0.put("Blah", Arrays.asList(new String[]{"d", "e", "f"}));
map1.put("Baz", Arrays.asList(new String[]{"3", "4", "5"}));
map1.put("Blah", Arrays.asList(new String[]{"g", "h", "i"}));
Set<String> retained = new HashSet<String>(map0.keySet());
retained.retainAll(map1.keySet());
for (String k: retained) {
System.out.printf("In map0: %s%n", map0.get(k));
System.out.printf("In map1: %s%n", map1.get(k));
}
<强>输出强>
In map0: [d, e, f]
In map1: [g, h, i]
答案 1 :(得分:0)
当然,它只是:
Iterator<String> itr = commonKeys.iterator();
while(itr.hasNext()){
String key = itr.next();
System.out.println("common key ::" + key);
System.out.println("list1 value ::" + propertiesMapList1.get(key));
System.out.println("list2 value ::" + propertiesMapList2.get(key));
}