【问题标题】:Grouping by in Java 8 stream to custom class rather than the origin class在 Java 8 流中分组到自定义类而不是原始类
【发布时间】:2019-05-13 10:34:46
【问题描述】:

我有一个 A 类,它有一些字段。

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

Class B{
    String x;
    String y;

}

假设我们有一个列表List<A>。通过使用 Collectors.groupingBy() ,是否可以获得输出 Map<String,List<B>> 而不是 Map<String,List<A>> ?其中Map 中的keyClass A 中的type 字段。

【问题讨论】:

  • Collectors.groupingBy(..., Collectors.mapping(....))

标签: java java-8 java-stream grouping


【解决方案1】:

当然 - 只需将 mapping() 收集器链接到 groupingBy() 收集器即可。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多