[英]Create a list of objects from another list using Java 8 streams
I have these three dto classes : 我有这三个dto课程:
public class OrganismeDTO {
private Long organismeId;
private String libelle;
private List<RoleDTO> rolesDTO;
}
public class RoleDTO {
private String lib;
private Long roleId;
private List<ProfilDTO> profilsDTO;
}
public class UtilisateurRoleDto {
private String organismeLib;
private String roleLib;
}
And in my DAO
I have a function that will return a list of UtilisateurRoleDto
. 在我的
DAO
我有一个函数,该函数将返回UtilisateurRoleDto
的列表。
What I want, is to create a list of OrganismeDTO
from UtilisateurRoleDto
list (Which I can get from my DAO), so for example, if I have a list of UtilisateurRoleDto
as following: 我想要的是从
UtilisateurRoleDto
列表中创建OrganismeDTO
列表(可以从我的DAO中获得),例如,如果我有一个UtilisateurRoleDto
列表,如下所示:
"Organisme 1", "Role 1"
"Organisme 1", "Role 2"
"Organisme 2", "Role 1"
"Organisme 2", "Role 3"
"Organisme 3", "Role 3"
I want a list of OrganismeDTO
in result as following (where each OrganismeDTO
has a list of RoleDTO
) : 我想要以下结果的
OrganismeDTO
列表(每个OrganismeDTO
都有一个RoleDTO
列表):
"Organisme 1" : ["Role 1", "Role 2"]
"Organisme 2" : ["Role 1", "Role 3"]
"Organisme 3" : ["Role 3"]
How can I implement this using Java 8 streams? 如何使用Java 8流实现此功能?
When I construct the RoleDTO
I need to inject RoleDTO.profilsDTO
by a list I get from a function that takes OrganismeDTO.roleId
and returns List<ProfilDTO>
. 当我构造
RoleDTO
我需要按列表插入RoleDTO.profilsDTO
,该列表是从一个采用OrganismeDTO.roleId
并返回List<ProfilDTO>
的函数获得的。
The only way I can think of at the moment is this: 我目前唯一想到的方法是:
Map<String, List<String>> collect = list.stream()
.collect(Collectors.groupingBy(UtilisateurRoleDto::getOrganismeLib,
Collectors.mapping(UtilisateurRoleDto::getRoleLib, Collectors.toList())));
List<OrganismeDTO> result = collect.entrySet().stream()
.map(entry -> new OrganismeDTO(entry.getKey(),
entry.getValue().stream()
.map(RoleDTO::new)
.collect(toList())))
.collect(Collectors.toList());
Firstly you can group your UtilisateurRoleDto
by it's organismeLib
field. 首先,你可以将你
UtilisateurRoleDto
通过它的organismeLib
场。 After that you process the obtained result and map it to your wanted entities. 之后,您处理获得的结果并将其映射到所需的实体。
You can do it with a custom collect(I added getters and some obvious constructors): 您可以使用自定义的collect(我添加了getter和一些显而易见的构造函数)来做到这一点:
Map<String, OrganismeDTO> map = dt.stream().collect(HashMap::new, (m, t) -> {
m.computeIfAbsent(t.getOrganismeLib(), x -> new OrganismeDTO(t.getOrganismeLib())).getRolesDTO().add(new RoleDTO(t.getRoleLib()));
}, (m1, m2) -> {
m2.forEach((k,v) -> {
OrganismeDTO organismeDTO = m1.get(k);
if (organismeDTO != null ) {
organismeDTO.getRolesDTO().addAll(v.getRolesDTO());
} else {
m1.put(k, v);
}
});
});
And then all that's left if to create List
from the values. 然后,如果要根据值创建
List
,则剩下的一切。
List<OrganismeDTO> list = map.values().stream().collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.