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

最佳答案

您当前的收集器.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属性。

08-05 13:24