简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM