猿问

如何从两个哈希图中检索公用键值对

我有两个哈希图:


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

为了从两个哈希图中获取公用键值对,我编写了以下逻辑:


uniquekeys.addAll(mapA.keySet());

uniquekeys.addAll(mapB.keySet());

然后使用中的键treeset: uniquekeys 从mapA和mapB中检索唯一的键值对。但这并没有给我mapA中所有键的详细信息。我知道这种方式是有缺陷的,但我无法提出适当的逻辑。谁能让我知道如何将mapA和mapB中常见的键值对检索到新的HashMap中?


吃鸡游戏
浏览 229回答 3
3回答

动漫人物

您可以通过以下方式使用Java 8 Streams进行操作:Map<String, String> commonMap = mapA.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; .filter(x -> mapB.containsKey(x.getKey()))&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

MMTTMM

尝试以下逻辑:Map<String, String> common = new HashMap<String, String>();&nbsp; &nbsp; &nbsp; &nbsp; for(String key : mapA.keySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(mapB.get(key) !=null ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(mapA.get(key).equals(mapB.get(key))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; common.put(key, mapA.get(key));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

大话西游666

使用番石榴实用程序集Set<String>&nbsp;intersectionSet&nbsp;=&nbsp;Sets.intersection(firstSet,&nbsp;secondSet);
随时随地看视频慕课网APP

相关分类

Java
我要回答