简体   繁体   中英

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

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> .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM