Java 8映射到对象列表,其中一个字段分组为一个列表 [英] Java 8 Map to a List of Objects with one field grouped into a List
本文介绍了Java 8映射到对象列表,其中一个字段分组为一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
新手问题.我有一个原始bean来自数据库,行为
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
}
我需要将其映射到具有多个Org的另一个Bean,这些组织按Employee ID分组到一个列表中. 一个雇员ID的组织只能是多个;注释字段必定是相同的.
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
}
努力入门.想到了下面的groupingBy
,但是返回了Map,我没有建立子列表.
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? */ .. ))
我的目标是转变为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
对象.
This maps the grouped results to your CustomDataBean
object.
输入:
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']
这篇关于Java 8映射到对象列表,其中一个字段分组为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文