How to recursively flatMap a stream?

I was asked to get each leaf of a node, which is a descandant node tree. I quickly realized that I could do this job on one line!

public Set<TreeNode<E>> getLeaves() {
    return getChildrenStream().flatMap(n -> n.getChildrenStream()).collect(toSet());
}

It was good at first sight, but he quickly came across StackOverflowExcepetionif the depth of the tree reaches ~ 10, which I cannot accept. Later I developed an implementation without recursion and thread (but with my brain fried), but I'm still wondering if there is a way to do recursive flatMapwith thread, because I found it impossible to do this without touching the internal elements of the thread. To do this, I need a new Op , for example RecursiveOps, or I will have to collect all the results at Seteach step and work with this Setlater:

Set<TreeNode<E>> prev = new HashSet<>();
prev.add(this);
while (!prev.isEmpty()) {
    prev = prev.stream().flatMap(n -> n.getChildrenStream()).collect(toSet());
}
return prev;

, . . op. . parellelize , . flatMap ?

PS1: TreeNode:

public class TreeNode<E> {
    // ...
    /**
     * Get a stream of children of the current node. 
     *
     */
    public Stream<TreeNode<E>> getChildrenStream(){
        // ...
    }

    public Set<TreeNode<E>> getLeaves() {
        // main concern
    }
}f
+4
1

, -, :

public static Set<TreeNode<String>> getAllLeaves(TreeNode<String> treeNode) {
    final Stream<TreeNode<String>> childrenStream = treeNode.getChildrenStream();
    if (childrenStream == null) {
        return new HashSet<>();
    }

    Set<TreeNode<String>> ownLeaves = treeNode.getLeaves();
    ownLeaves.addAll(childrenStream.flatMap(stringTreeNode -> getAllLeaves(stringTreeNode).parallelStream())
            .collect(Collectors.toSet()));

    return ownLeaves;
}

. , flatMap. , , , flatMap, Set, , . , -1000, .

0

All Articles