I have a List of String like:
List locations = Arrays.asList("US:5423","US:6321","CA:1326","AU:5631");
And I want to convert in Map> as like:
AU = [5631]
CA = [1326]
US = [5423, 6321]
I have tried this code and it works but in this case, I have to create a new class GeoLocation.java.
List locations=Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
Map> 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;
}
}
But I want to know, Is there any way to convert List to Map> without introducing new class.
解决方案
You may do it like so:
Map> locationMap = locations.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
A much more better approach would be,
private static final Pattern DELIMITER = Pattern.compile(":");
Map> locationMap = locations.stream()
.map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
Update
As per the following comment, this can be further simplified to,
Map> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));