示例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()来转换
import java.util.*;
import java.util.regex.*;
import java.util.stream.*;
public class Main {
private static final Pattern DELIMITER = Pattern.compile(":");
public static void main(String[] args) {
List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
// 使用 Pattern 和 Stream API 将列表转换为 Map<String, List<String>>
Map<String, List<String>> locationMap = locations.stream()
.map(DELIMITER::split)
.collect(Collectors.groupingBy(
arr -> arr[0], // 根据 ":" 分割后的第一个元素作为键
Collectors.mapping(
arr -> arr[1], // 取 ":" 后面的部分作为值
Collectors.toList()
)
));
// 打印结果
System.out.println(locationMap);
}
}
2、通过forEach循环转换
import java.util.*;
public class Main {
public static void main(String[] args) {
// 示例数据
List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
// 调用 groupByCountry 方法
Map<String, Set<String>> map = groupByCountry(locations);
// 打印结果
System.out.println(map);
}
// 定义 groupByCountry 方法
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;
}
}
3、使用Stream API和split()
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
// 使用 Java 8 Stream API 将列表转换为 Map<String, List<String>>
Map<String, List<String>> map = locations.stream()
.collect(Collectors.groupingBy(
location -> location.split(":")[0], // 根据 ":" 分割,取第一个部分作为键
Collectors.mapping(
location -> location.split(":")[1], // 取 ":" 后面的部分作为值
Collectors.toList()
)
));
System.out.println(map);
}
}