我有一个
Map<String,String>
,我想将其转换为 Map<String, List<String>>
。可以使用如下的 for 循环轻松完成。但是我可以在 Java 8 中使用 stream()
做同样的事情吗?
样本
Map<String,String>
:{"Country":"US,Japan","Food":"Burger,Cake"}
代码:
Map<String, List<String>> newMap = null;
for (String tmp: sampleMap.keySet()){
newMap.putIfAbsent(tmp, sampleMap.get(tmp).split(","));
}
你可以试试这个:
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1,value2");
map.put("key2", "value3,value4,value5");
map.put("key3", "value6");
Map<String, List<String>> result = map.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> Arrays.asList(e.getValue().split(","))
));
System.out.println(result); //-> Test the Output
}
}