Map and Groupby in one go

Viewed 48

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?

2 Answers

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