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

时间:2019-05-21 09:43:33

标签: java generics java-8 java-stream collectors

如何使用收集器将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))
    }

2 个答案:

答案 0 :(得分:14)

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

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

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

这是假设您有一些Pojo构造函数,该构造函数接收GenericDAO实例或相关的GenericDAO属性。

答案 1 :(得分:6)

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