java - 如何根据分隔符将 List<String> 转换为 Map<String,List<String>>

标签 java lambda java-8 java-stream

我有一个字符串列表,例如:

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>>不引入新类(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())));

更新

根据下面的评论,这可以进一步简化为,

Map<String, List<String>> locationMap = locations.stream().map(DELIMITER::split)
    .collect(Collectors.groupingBy(a -> a[0], 
        Collectors.mapping(a -> a[1], Collectors.toList())));

关于java - 如何根据分隔符将 List<String> 转换为 Map<String,List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56389575/

相关文章:

C# lambda 未命名参数

java - IntSummaryStatistics 的 summaryStatistics 方法

c# - 向 Lambda 函数添​​加断点

c++ - 您可以在类的初始化列表中使用 Lambda 吗?

Java:System.exit() 参数

java - 如何避免 Firefox 中的窗口下载​​弹出窗口使用 Java selenium?我需要自动下载而不询问弹出窗口吗?

java - 在一组对象中查找连续的字符串属性序列(通过流 API)

lambda - Java 8 - 如何对列表映射中的所有列表元素求和

java - 在带有 spring-boot rest 和 Swagger 的 header 中使用 utf-8 字符时响应未加载

java - onCommand() 设置正确但根本没有执行