Search code examples
javagenericsjava-8java-streamcollectors

Use Collectors to convert List to Map of Objects - Java


How do I use Collectors in order to convert a list of DAOs, to a Map<String, List<Pojo>>

daoList looks something like this:

[0] : id = "34234", team = "gools", name = "bob", type = "old"
[1] : id = "23423", team = "fool" , name = "sam", type = "new"
[2] : id = "34342", team = "gools" , name = "dan", type = "new"

I want to groupBy 'team' attribute and have a list for each team, as follows:

"gools":
       ["id": 34234, "name": "bob", "type": "old"],
       ["id": 34342, "name": "dan", "type": "new"]

"fool":
       ["id": 23423, "name": "sam", "type": "new"]

Pojo looks like this:

@Data
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class Pojo{

    private String id;
    private String name;
    private String type;
}

This is how I'm trying to do that, obviously the wrong way:

public Team groupedByTeams(List<? extends GenericDAO> daoList)
    {

        Map<String, List<Pojo>> teamMap= daoList.stream()
            .collect(Collectors.groupingBy(GenericDAO::getTeam))
    }

Solution

  • Your current collector - .collect(Collectors.groupingBy(GenericDAO::getTeam)) - is generating a Map<String,List<? extends GenericDAO>>.

    In order to generate a Map<String, List<Pojo>>, you have to convert your GenericDAO instances into Pojo instances by chaining a Collectors.mapping() collector to the Collectors.groupingBy() collector:

    Map<String, List<Pojo>> teamMap = 
        daoList.stream()
               .collect(Collectors.groupingBy(GenericDAO::getTeam,
                                              Collectors.mapping (dao -> new Pojo(...),
                                                                  Collectors.toList())));
    

    This is assuming you have some Pojo constructor that receives a GenericDAO instance or relevant GenericDAO properties.