2 回答
TA贡献1789条经验 获得超10个赞
我重新创建了您的示例,这应该可以满足您的要求。如果对代码还有任何其他问题,请告诉我。
HashMap<String,List<String>> hashMap = new HashMap<>();
hashMap.put("k1", Arrays.asList("v1","v2"));
hashMap.put("k2", Arrays.asList("v2"));
hashMap.put("k3", Arrays.asList("v1"));
HashMap<String,List<String>> result = new HashMap<>();
hashMap.forEach((s, strings) ->{
for (String element : strings){
List<String> tempList = new ArrayList<>();
if(result.containsKey(element)){
tempList = result.get(element);
}
tempList.add(s);
result.put(element, tempList);
}
});
TA贡献1878条经验 获得超4个赞
假设你有一个Map<String,List<String>> myMap = ...
Map<String,List<String>> reversed =
myMap.values().stream().flatMap(List::stream).distinct()
.map(v -> new AbstractMap.SimpleEntry<>(v,
myMap.entrySet().stream()
.filter(e -> e.getValue().contains(v))
.map(Map.Entry::getKey)
.collect(Collectors.toList())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(reversed);
添加回答
举报