使用收集器将列表转换为对象映射 - Java

2022-09-03 06:11:19

如何使用收集器将 DAO 列表转换为Map<String, List<Pojo>>

daoList 看起来像这样:

[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"

我想按“团队”属性分组,并为每个团队提供一个列表,如下所示:

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

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

Pojo看起来像这样:

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

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

这就是我试图这样做的方式,显然是错误的方式:

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

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

答案 1

您的电流收集器 - - 正在生成一个 ..collect(Collectors.groupingBy(GenericDAO::getTeam))Map<String,List<? extends GenericDAO>>

为了生成 ,您必须通过将收集器链接到收集器来将实例转换为实例:Map<String, List<Pojo>>GenericDAOPojoCollectors.mapping()Collectors.groupingBy()

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

这假设您有一些接收实例或相关属性的构造函数。PojoGenericDAOGenericDAO


答案 2

用作:mapping

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

其中,诸如 此类的转换可能如下所示:convertGenericDaoToTeam

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

推荐