Map and Groupby in one go

KayV :

I have a model class as follows:

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;

}

I have the following requirement:

  1. Convert the List<CCP> into Map<pid, List<cid>>

that is, i want to convert the list of CCP objects into a map having pid as key and a list of associated cids as values.

I tried the following things:

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

But this gives the list of CCP only.

How can i get List of cid here instead of CCP?

Eran :

Use mapping:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75060&siteId=1