首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java 8函数式编程

Java 8函数式编程
EN

Stack Overflow用户
提问于 2020-06-12 16:29:52
回答 1查看 45关注 0票数 0

我正在寻找实现小通用函数,以执行树结构上的不同操作。在收集结果方面需要帮助。

示例:

代码语言:javascript
复制
public static <R> R collect(final Constraint root, Function<Constraint, R> function) {      
        if(root == null) { // return here }

        //apply function to current node and collect result here
        function.apply(root);

        // If has more children recurse.
        if(root.getConstraints() != null && !root.getConstraints().isEmpty()) {
            root.getConstraints().forEach(e -> collect(e, function));
        }
}

这可以用于以下情况:-收集没有子节点的所有节点-收集所有具有子节点的节点-收集满足某些特定条件的节点。

EN

回答 1

Stack Overflow用户

发布于 2020-06-12 17:29:56

Map怎么样?

代码语言:javascript
复制
public static <R> Map<Constraint, R> collect(final Constraint root, Function<Constraint, R> function) {
    Map<Constraint, R> results = new HashMap<>();
    collect(root, function, results);
    return results;
}

private static <R> void collect(final Constraint root, Function<Constraint, R> function, Map<Constraint, R> results) {
    if (root != null) { // return here }

        //apply function to current node and collect result here
        results.put(root, function.apply(root));

        // If has more children recurse.
        if (root.getConstraints() != null && !root.getConstraints().isEmpty()) {
            root.getConstraints().forEach(e -> collect(e, function, results));
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62340463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档