如何在java8中使用Lambda获得相同的结果 for(组实体组实体:组){ //查找属于组的角色 集合groupRoles=groupEntity.getRoles(); for(RoleEntity RoleEntity:groupRoles){ if(roleEntity.getType()==RoleType.MODULE){ ModuleEntity module=roleEntity.getModule(); 如果(!modules.contains(模块)){ //防止重复模块 模块。添加(模块); } }else if(roleEntity.getType()==RoleType.OUTLINE){ OutlineEntity outline=roleEntity.getOutline(); //防止重复的轮廓 如果(!outline.contains(outline)){ 大纲。添加(大纲); } } } }

如何在java8中使用Lambda获得相同的结果 for(组实体组实体:组){ //查找属于组的角色 集合groupRoles=groupEntity.getRoles(); for(RoleEntity RoleEntity:groupRoles){ if(roleEntity.getType()==RoleType.MODULE){ ModuleEntity module=roleEntity.getModule(); 如果(!modules.contains(模块)){ //防止重复模块 模块。添加(模块); } }else if(roleEntity.getType()==RoleType.OUTLINE){ OutlineEntity outline=roleEntity.getOutline(); //防止重复的轮廓 如果(!outline.contains(outline)){ 大纲。添加(大纲); } } } },lambda,java-8,Lambda,Java 8,我想用Lambda得到同样的结果。我试过了,但结果是List List roles=groups.stream().map(g->g.getRoles().stream()) .filter(distinctByKey(RoleEntity::getId)) .collect(收集器.toList()) .stream().filter(r->RoleType.MODULE.equals(r.getType())) .collect(收集器.toList()) ).collect(Collect

我想用Lambda得到同样的结果。我试过了,但结果是
List

List roles=groups.stream().map(g->g.getRoles().stream())
.filter(distinctByKey(RoleEntity::getId))
.collect(收集器.toList())
.stream().filter(r->RoleType.MODULE.equals(r.getType()))
.collect(收集器.toList())
).collect(Collectors.toList());

我知道lambda对编码器来说是个很棒的主意。但是学习它似乎不那么容易。希望有人能帮我解决问题。谢谢!:XD

您需要使用
groupingBy

    List<List<RoleEntity>> roles= groups.stream().map(g->g.getRoles().stream()
            .filter(distinctByKey(RoleEntity::getId))
            .collect(Collectors.toList())
            .stream().filter(r->RoleType.MODULE.equals(r.getType()))
            .collect(Collectors.toList())
            ).collect(Collectors.toList());
Map roleTypeSetMap=groups.stream()
.flatMap(g->g.getRoles().stream())
.collect(Collectors.groupingBy(RoleEntity::getType,Collectors.mapping(r->(r.getType()==RoleType.MODULE)?r.getModule():r.getOutline(),Collectors.toSet());

如果
ModuleEntity
OutlineEntity
有一个共同的父对象(比如
实体
)我们可以将
Set
更改为
Set

ModuleEntity
OutlineEntity
是不同的。它们没有共同的父级。我想知道如何将
Set
转换为
Set
Set
此解决方案假定角色类型为模块或角色类型outline@Misha是的,如果不需要其他类型,OP需要进行筛选,或者切换大小写以映射不同的类型
    List<List<RoleEntity>> roles= groups.stream().map(g->g.getRoles().stream()
            .filter(distinctByKey(RoleEntity::getId))
            .collect(Collectors.toList())
            .stream().filter(r->RoleType.MODULE.equals(r.getType()))
            .collect(Collectors.toList())
            ).collect(Collectors.toList());
    Map<RoleType, Set<Object>> roleTypeSetMap = groups.stream()
            .flatMap(g -> g.getRoles().stream())
            .collect(Collectors.groupingBy(RoleEntity::getType, Collectors.mapping(r -> (r.getType() == RoleType.MODULE) ? r.getModule() : r.getOutline(), Collectors.toSet())));