Shashank Dwivedi
Shashank Dwivedi

Reputation: 407

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.

Upvotes: 0

Views: 55

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 32831

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));
        }
    }
}

Upvotes: 1

Related Questions