我正在寻找实现小通用函数,以执行树结构上的不同操作。在收集结果方面需要帮助。
示例:
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));
}
}这可以用于以下情况:-收集没有子节点的所有节点-收集所有具有子节点的节点-收集满足某些特定条件的节点。
发布于 2020-06-12 17:29:56
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));
}
}
}https://stackoverflow.com/questions/62340463
复制相似问题