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);
添加回答
舉報