猿问

Java 8 List<Foo> 到 Map<String, Map<String

我有以下课程:


public class Foo {

    private String areaName;

    private String objectName;

    private String lineName;

}

现在我想将 a 转换List<Foo>为Map<String, Map<String, List<String>>>. 我找到了这个答案,它帮助我开发了以下代码:


Map<String, Map<String, List<String>>> testMap = foos.stream().collect(Collectors.groupingBy(e -> e.getAreaName(),

        Collectors.groupingBy(e -> e.getObjectName(), Collectors.collectingAndThen(Collectors.toList(),

                e -> e.stream().map(f -> f.getLineName())))));

此代码的唯一问题是它应该转换为List<String>. 我找不到转换Foo为List那部分的方法。


另一种方法导致Map<String, Map<String, List<Foo>>>:


Map<Object, Map<Object, List<Foo>>> testMap = ventures.stream().collect(Collectors.groupingBy(e -> e.getAreaName(),

        Collectors.groupingBy(e -> e.getObjectName(), Collectors.toList())));

我需要做什么来改变,以获得Map<String, Map<String, List<String>>>从List<Foo>?


Cats萌萌
浏览 164回答 1
1回答

幕布斯6054654

为了获得List与Stream元素类型不同的类型,您应该将Collectors.mapping收集器链接到groupingBy:Map<String, Map<String, List<String>>> testMap =&nbsp;&nbsp; &nbsp; foos.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Foo::getAreaName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.groupingBy(Foo::getObjectName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Collectors.mapping(Foo::getLineName,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.toList()))));
随时随地看视频慕课网APP

相关分类

Java
我要回答