Grouping by in Java 8 stream to custom class rather than the origin class

落花浮王杯 提交于 2019-12-13 22:40:43

问题


I have a class A which has some fields.

Class A{
 String type;
 String x;
 String y;
}

Class B{
    String x;
    String y;

}

Let's say we have a list List<A>. By using Collectors.groupingBy() , is it possible to get output Map<String,List<B>> instead Map<String,List<A>> ? where key in the Map is type field in Class A.


回答1:


Of course - just chain a mapping() collector to the groupingBy() collector.

Map<String,List<B>> map =
    listA.stream()
         .collect(Collectors.groupingBy(A::getType,
                                        Collectors.mapping(a->new B(a.getX(),a.getY()),
                                                           Collectors.toList())));


来源:https://stackoverflow.com/questions/56110564/grouping-by-in-java-8-stream-to-custom-class-rather-than-the-origin-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!