0

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.

4
  • It sounds like you need your 'collect` method to return a tree of Rs... Commented Jun 12, 2020 at 8:34
  • Yes, I kept it R trying to keep it more generic to get List, Set, Array, boolean etc Commented Jun 12, 2020 at 8:43
  • what help are you looking forward to? also, while sharing the code, do ensure the example is reproducible. Commented Jun 12, 2020 at 9:11
  • 1
    “I kept it R” makes no sense when the result is not supposed to be 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. Commented Jun 12, 2020 at 12:49

1 Answer 1

1

How about a 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));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.