user3819295
user3819295

Reputation: 861

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))
    }

Upvotes: 16

Views: 1075

Answers (2)

Eran
Eran

Reputation: 393771

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.

Upvotes: 15

Naman
Naman

Reputation: 31868

Use mapping as:

public Map<String, List<Team>> groupedByTeams(List<? extends GenericDAO> daoList) {
    Map<String, List<Team>> teamMap = daoList.stream()
            .collect(Collectors.groupingBy(GenericDAO::getTeam,
                    Collectors.mapping(this::convertGenericDaoToTeam, Collectors.toList())));
    return teamMap;
}

where a conversion such as convertGenericDaoToTeam could be possibly like:

Team convertGenericDaoToTeam(GenericDAO genericDAO) {
    return new Team(genericDAO.getId(), genericDAO.getName(), genericDAO.getType());
}

Upvotes: 7

Related Questions