我需要使用java 8将<String, List<String>>映射为Map<String,String>,并假定值是唯一的。例如,
输入地图-
{"Fruit" -> ["apple","orange"], "Animal" -> ["Dog","Cat"]}输出图
{"apple" -> "Fruit", "orange" -> "Fruit", "Dog"->"Animal", "Cat" -> "Animal"}Map <String, String> outputMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : inputMap.entrySet()) {
entry.getValue().forEach(value -> outputMap.put(value, entry.getKey()));
} 是这样的吗?我们可以使用streams java 8来实现这一点吗?
发布于 2019-10-02 08:16:24
你试试这边
Map <String, String> updatedMap = new HashMap<>();
oldMap.keySet()
.forEach(i -> oldMap.get(i)
.forEach(k -> updatedMap.put(k, i)));发布于 2019-10-01 09:08:25
就像这样:
public class InverterMap {
public static void main(String[] args) {
Map<String, List<String>> mp = new HashMap<String, List<String>>();
mp.put("Fruit", Arrays.asList("Apple", "Orange"));
mp.put("Animal", Arrays.asList("Dog", "Cat"));
System.out.println(mp); // It returned {Fruit=[Apple, Orange], Animal=[Dog, Cat]}
Map<String, String> invertMap = mp.entrySet().stream().collect(HashMap::new,
(m, v) -> v.getValue().forEach(k -> m.put(k, v.getKey())), Map::putAll);
System.out.println(invertMap);// It returned {Apple=Fruit, Cat=Animal, Orange=Fruit, Dog=Animal}
}
}https://stackoverflow.com/questions/58178078
复制相似问题