[英]Java 8 Functional programming
I am looking for implementing little generic functions to perform different operations on tree structure.我正在寻找实现小的通用函数来对树结构执行不同的操作。 Need help in collecting results.在收集结果时需要帮助。
Example:例子:
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));
}
}
This may be used in situations such as - collect all nodes with no children - collect all nodes having children - collect nodes with satisfies some specific condition.这可以用于以下情况 - 收集没有孩子的所有节点 - 收集所有有孩子的节点 - 收集满足某些特定条件的节点。
How about a Map
? Map
怎么样?
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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.