StupidPz
StupidPz

Reputation: 451

How to get the same result with Lambda in java8

for (GroupEntity groupEntity : groups) {
        // find roles belongs to group
        Collection<RoleEntity> groupRoles = groupEntity.getRoles();
        for (RoleEntity roleEntity : groupRoles) {
            if (roleEntity.getType() == RoleType.MODULE) {
                ModuleEntity module = roleEntity.getModule();
                if (!modules.contains(module)) {
                    // prevent duplicate module
                    modules.add(module);
                }
            } else if (roleEntity.getType() == RoleType.OUTLINE) {
                OutlineEntity outline = roleEntity.getOutline();
                //prevent duplicate outline
                if (!outlines.contains(outline)) {
                    outlines.add(outline);
                }
            }
        }
    }

I want to get the same result with Lambda.And i tried But it ruturned List<List<RoleEntity>>.

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

i konw lambda is a amazing idea for coder.But learning it seems not so easy.Hope somebody can help me solve problems.Thanks! :XD

Upvotes: 3

Views: 86

Answers (1)

Saravana
Saravana

Reputation: 12817

You need to use groupingBy

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

if ModuleEntity and OutlineEntity have a common parent (Let's say Entity) we can change Set<Object> to Set<Entity>

Upvotes: 7

Related Questions