在Java 8流中按分组到自定义类,而不是原始类 [英] Grouping by in Java 8 stream to custom class rather than the origin class

查看:81
本文介绍了在Java 8流中按分组到自定义类,而不是原始类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A类,其中包含一些字段.

I have a class A which has some fields.

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字段.

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.

推荐答案

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

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())));

这篇关于在Java 8流中按分组到自定义类,而不是原始类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆