【问题标题】:Java 8 Map to a List of Objects with one field grouped into a ListJava 8 映射到一个对象列表,其中一个字段分组到一个列表中
【发布时间】:2019-05-10 15:08:00
【问题描述】:

新手问题。我有一个原始 bean 来自 DB 逐行作为

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

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

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

努力开始。正在考虑groupingBy,如下所示,但它返回一个地图,我没有建立一个子列表。

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

我的目标是转换后的List&lt;CustomDataBean&gt;

【问题讨论】:

  • 只是为了确保我理解正确:您的输入是DataBeanList,并且您想将具有相同employeeIdDataBeans 分组到CustomDataBeans ?
  • 尝试适配器设计模式。
  • 一个员工可以有不同的组织。我得到了逐行的结果,并且需要创建一个bean,其中 Employee 有一个 List 用于他所属的组织。换句话说,该员工的所有组织都包装在一个列表字段中。

标签: java collections java-stream pojo


【解决方案1】:

你可以用这个:

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']

【讨论】:

  • 工作,谢谢 - 真的很简单。我没有意识到 1-param groupingBy 会给出 Map&lt;String,DataBean&gt;(从那时起就很简单了)。
  • Collectors.groupingBy(DataBean::getEmployeeId)Collectors.groupingBy(DataBean::getEmployeeId, Collectors.toList()) 相同。默认使用toList() 收集器。
【解决方案2】:

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

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

进一步,实现您的目标,获得List&lt;CustomDataBean&gt;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多