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.
Rs...R, but a structured type, collection, map, tree, whatever, containing multiple Rs. If you want to be flexible regarding the actual return type, you need another function parameter telling how to construct the result or a node of the result structure.