Java 8 映射到一个对象列表,其中一个字段分组到一个列表中

Java 8 Map to a List of Objects with one field grouped into a List

菜鸟问题。我有一个原始的 bean 来自 DB row-by-row

public class DataBean {
   private Integer employeeId;
   private String org;
   private String comments;
   // + Constructors, getters/setters
}

我需要将它映射到一个不同的 bean,其中多个 Org 按员工 ID 分组到一个列表中。 一个EmployeeID只能有多个Orgs; Comments 字段保证相同。

public class CustomDataBean {
   private Integer employeeId;
   private List<String> orgs;
   private String comments;
   // + Constructors, getters/setters
}

努力开始。正在考虑 groupingBy 如下所示,但 returns 是一个地图,我没有构建子列表。

Map<Integer, List<String>> temp = origData.stream().collect(
    Collectors.groupingBy(OrigBean::getEmployeeId,
    /* 2nd param? */ .. ))

我的目标是变身List<CustomDataBean>

你可以使用这个:

List<CustomDataBean> result = origData.stream()
        .collect(Collectors.groupingBy(DataBean::getEmployeeId))
        .entrySet().stream()
        .map(e -> new CustomDataBean(
                e.getKey(),
                e.getValue().stream().map(DataBean::getOrg).collect(Collectors.toList()),
                e.getValue().get(0).getComments()))
        .collect(Collectors.toList());

这会将分组结果映射到您的 CustomDataBean 对象。

对于输入:

List<DataBean> origData = Arrays.asList(
        new DataBean(1, "a", "c"),
        new DataBean(1, "b", "c"),
        new DataBean(1, "c", "c"),
        new DataBean(2, "a", "d"),
        new DataBean(2, "c", "d")
);

结果将是这样的:

CustomDataBean[employeeId=1, orgs=[a, b, c], comments='c']
CustomDataBean[employeeId=2, orgs=[a, c], comments='d']

要回答这两个问题,请使用 Collectors.mapping 作为下游:

Map<Integer, List<String>> temp = origData.stream().collect(
        Collectors.groupingBy(DataBean::getEmployeeId,
                Collectors.mapping(DataBean::getOrg, Collectors.toList())));

此外,实现您获得 List<CustomDataBean> 的目标:

List<CustomDataBean> goal = origData.stream()
        .map(a -> new CustomDataBean(a.getEmployeeId(), temp.get(a.employeeId), a.getComments()))
        .collect(Collectors.toList());