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

北战南征 提交于 2021-02-08 05:36:16

问题


Newbie question. I have an original bean coming from the DB row-by-row as

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

I need to map it to a different bean with multiple Org's grouped by Employee ID into a List. Only Orgs can be multiple for an EmployeeID; the Comments field is guaranteed to be the same.

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

Struggling to get started. Was thinking of groupingBy such as the below but that returns a Map, and I'm not building a sub-List.

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

My goal is a transformed List<CustomDataBean>.


回答1:


You just can use this:

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

This maps the grouped results to your CustomDataBean object.

For the input:

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")
);

The result will be this:

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



回答2:


To answer both the questions, use Collectors.mapping as the downstream as :

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

and further, achieve your goal to obtain a List<CustomDataBean> as:

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


来源:https://stackoverflow.com/questions/56080335/java-8-map-to-a-list-of-objects-with-one-field-grouped-into-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!