【发布时间】:2019-05-31 06:12:32
【问题描述】:
我有一个字符串列表,例如:
List<String> locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
我想在Map<String, List<String>> 中转换为:
AU = [5631]
CA = [1326]
US = [5423, 6321]
我已经尝试过这段代码,它可以工作,但在这种情况下,我必须创建一个新类GeoLocation.java。
List<String> locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map<String, List<String>> locationMap = locations
.stream()
.map(s -> new GeoLocation(s.split(":")[0], s.split(":")[1]))
.collect(
Collectors.groupingBy(GeoLocation::getCountry,
Collectors.mapping(GeoLocation::getLocation, Collectors.toList()))
);
locationMap.forEach((key, value) -> System.out.println(key + " = " + value));
GeoLocation.java
private class GeoLocation {
private String country;
private String location;
public GeoLocation(String country, String location) {
this.country = country;
this.location = location;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
但我想知道,有什么方法可以在不引入新类的情况下将List<String> 转换为Map<String, List<String>>。
【问题讨论】:
-
Java 缺少元组的问题再次来袭 :(
标签: java lambda java-8 java-stream