4

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
KayV
  • 12,987
  • 11
  • 98
  • 148

2 Answers2

4

Use mapping:

Map<Integer, List<Integer>> xxx = 
    ccplist.stream()
           .collect(Collectors.groupingBy(CCP::getPId,
                                          Collectors.mapping(CCP::getCId,
                                                             Collectors.toList())));
Eran
  • 387,369
  • 54
  • 702
  • 768
2
 ccplist.stream()
         .collect(Collectors.groupingBy(
               CCP::getPId,
               Collectors.mapping(CCP::getCId, Collectors.toList())));
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 1
    Eran got there 47 seconds before you with an identical solution, you so I gave him the upvote instead (even though I prefer your indentation style). – DodgyCodeException Nov 13 '18 at 13:46