【问题标题】:How to get the same result with Lambda in java8如何在 java8 中使用 Lambda 获得相同的结果
【发布时间】:2023-03-23 23:30:01
【问题描述】:
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);
                }
            }
        }
    }

我想用 Lambda 得到同样的结果。我试过了,但结果却是List&lt;List&lt;RoleEntity&gt;&gt;

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

我知道 lambda 对 coder 来说是一个了不起的想法。但是学习它似乎并不那么容易。希望有人可以帮助我解决问题。谢谢! :XD

【问题讨论】:

    标签: lambda java-8


    【解决方案1】:

    你需要使用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())));
    

    如果ModuleEntityOutlineEntity 有一个共同的父级(比如说Entity),我们可以将Set&lt;Object&gt; 更改为Set&lt;Entity&gt;

    【讨论】:

    • ModuleEntityOutlineEntity 不同。它们没有共同的父级。我想知道如何将 Set&lt;Object&gt; 转换为 Set&lt;ModuleEntity&gt; Set&lt;T&gt;
    • 此解决方案假定角色类型是模块或大纲
    • @Misha true,如果不需要其他类型,OP需要过滤,或者切换大小写以映射不同的类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多