[英]Want to fetch common key and it's multiple values in two hashmaps
我已經初始化了兩個哈希圖,如下所示
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());
}
在基於其中一個鍵集創建新的Set
之后,可以使用Set.retainAll
,然后獲取兩個地圖的每個鍵。
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]
當然,這只是:
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.