Map 和 Groupby 合二为一

Map and Groupby in one go

我有一个模型class如下:

public class CCP implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "p_id")
    private Integer pId;

    @Id
    @Column(name = "c_id")
    private Integer cId;

    @Column(name = "priority")
    private Integer priority;

}

我有以下需求:

  1. List<CCP>转换为Map<pid, List<cid>>

也就是说,我想将 CCP 对象列表转换为以 pid 作为键并以关联的 cids 列表作为值的映射。

我尝试了以下操作:

Map<Integer, List<CCP>> xxx = ccplist.stream()
                .collect(Collectors.groupingBy(ccp -> ccp.getPId()));

但这只给出了中共的名单。

如何在此处获取 cid 列表而不是 CCP?

使用mapping:

Map<Integer, List<Integer>> xxx = 
    ccplist.stream()
           .collect(Collectors.groupingBy(CCP::getPId,
                                          Collectors.mapping(CCP::getCId,
                                                             Collectors.toList())));
 ccplist.stream()
         .collect(Collectors.groupingBy(
               CCP::getPId,
               Collectors.mapping(CCP::getCId, Collectors.toList())));