如何转换List< String>映射到Map< String,List< String>>基于分度计 [英] How to convert List<String> to Map<String,List<String>> based on a delimeter
本文介绍了如何转换List< String>映射到Map< String,List< String>>基于分度计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串列表,如:
I have a List of String like:
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
.
I have tried this code and it works but in this case, I have to create a new class 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>>
.
But I want to know, Is there any way to convert List<String>
to Map<String, List<String>>
without introducing new class.
推荐答案
您可以这样做:
Map<String, List<String>> locationMap = locations.stream()
.map(s -> s.split(":"))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
一种更好的方法,
private static final Pattern DELIMITER = Pattern.compile(":");
Map<String, List<String>> locationMap = locations.stream()
.map(s -> DELIMITER.splitAsStream(s).toArray(String[]::new))
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
更新
根据以下评论,可以将其进一步简化为
As per the following comment, this can be further simplified to,
Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
.collect(Collectors.groupingBy(a -> a[0],
Collectors.mapping(a -> a[1], Collectors.toList())));
这篇关于如何转换List< String>映射到Map< String,List< String>>基于分度计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文