gpt4 book ai didi

java - 想要获取公共(public)键并且它是两个 HashMap 中的多个值

转载 作者:行者123 更新时间:2023-12-01 12:50:24 29 4
gpt4 key购买 nike

我已经初始化了两个 HashMap ,如下

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);

我能够获取两个 HashMap 中的公共(public)键,我如何获取相应的值?

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]

关于java - 想要获取公共(public)键并且它是两个 HashMap 中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24261149/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com