本文主要介绍Java中将指定List<String>类型数据转换成Map<String,List<String>>类型的几种方法。通过stream()或foreach循环实现。

示例List<String>类型数据

List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

将上面locations转换成Map<String, List<String>>,例如:

AU = [5631]
CA = [1326]
US = [5423, 6321]

1、通过stream()来转换

private static final Pattern DELIMITER = Pattern.compile(":");
Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));

Map<String, List<String>> locationMap = locations.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));

2、通过forEach循环转换

public static Map<String, Set<String>> groupByCountry(List<String> locations) {
Map<String, Set<String>> map = new HashMap<>();
locations.forEach(location -> {
String[] parts = location.split(":");
map.compute(parts[0], (country, codes) -> {
codes = codes == null ? new HashSet<>() : codes;
codes.add(parts[1]);
return codes;
});
});
return map;
}

推荐文档