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

gene b. :

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

Samuel Philipp :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113479&siteId=1