将哈希映射值交换为键

我有一个哈希图


{

k1 = {v1, v2},

k2 = {v2},

k3 = {v1}

}

我的要求是构建一个新的哈希映射,其中旧映射中的值作为键,键作为值列表。新的 hasmap 看起来像


{

v1 = {k1, k3},

v2 = {k1, k2}

}


守候你守候我
浏览 94回答 2
2回答

至尊宝的传说

我重新创建了您的示例,这应该可以满足您的要求。如果对代码还有任何其他问题,请告诉我。HashMap<String,List<String>> hashMap = new HashMap<>();&nbsp; &nbsp; hashMap.put("k1", Arrays.asList("v1","v2"));&nbsp; &nbsp; hashMap.put("k2", Arrays.asList("v2"));&nbsp; &nbsp; hashMap.put("k3", Arrays.asList("v1"));&nbsp; &nbsp; HashMap<String,List<String>> result = new HashMap<>();&nbsp; &nbsp; hashMap.forEach((s, strings) ->{&nbsp; &nbsp; &nbsp; &nbsp; for (String element : strings){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String> tempList = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(result.containsKey(element)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempList = result.get(element);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempList.add(s);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.put(element, tempList);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });

UYOU

假设你有一个Map<String,List<String>> myMap = ...&nbsp; &nbsp; Map<String,List<String>> reversed =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myMap.values().stream().flatMap(List::stream).distinct()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(v ->&nbsp; new AbstractMap.SimpleEntry<>(v,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myMap.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(e -> e.getValue().contains(v))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Map.Entry::getKey)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList())))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));&nbsp; &nbsp; System.out.println(reversed);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java