当前位置: 首页 > 工具软件 > Country List > 使用案例 >

java map string list_Java 将List<String> 转换成 Map<String,List<String>>的几种方法

柯乐童
2023-12-01

示例List类型数据List locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");

将上面locations转换成Map>,例如:AU = [5631]

CA = [1326]

US = [5423, 6321]

1、通过stream()来转换private static final Pattern DELIMITER = Pattern.compile(":");

Map> locationMap = locations.stream().map(DELIMITER::split)

.collect(Collectors.groupingBy(a -> a[0],

Collectors.mapping(a -> a[1], Collectors.toList())));

或Map> 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> groupByCountry(List locations) {

Map> 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;

}

 类似资料: