java - How to recursively flatMap a stream? -


i asked retrieve every leaf node descandant of tree node. got idea job in 1 line!

public set<treenode<e>> getleaves() {     return getchildrenstream().flatmap(n -> n.getchildrenstream()).collect(toset()); } 

it @ first glance, ran stackoverflowexcepetionif tree depth reaches ~10, can't accept. later developed implementation without recursion , stream (but brain roasted), i'm still wondering if there way recursive flatmaps stream, because found impossible without touching stream internals. it'll need new op, recursiveops that, or have collect results set every step, , operate on set later:

set<treenode<e>> prev = new hashset<>(); prev.add(this); while (!prev.isempty()) {     prev = prev.stream().flatmap(n -> n.getchildrenstream()).collect(toset()); } return prev; 

not seems be. streams meant pipeline. result , intermediate results not computed until terminal op added. above approach appearently violates principle. it's not easy parellelize streams, too. can recursively flatmap without manually computing intermediate results?

ps1: treenode declaration:

public class treenode<e> {     // ...     /**      * stream of children of current node.       *      */     public stream<treenode<e>> getchildrenstream(){         // ...     }      public set<treenode<e>> getleaves() {         // main concern     } }f 

not entirely sure if interested in:

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

out of box see few inconvenients method. return empty set last iteration , it's creating streams flatmap. believe looking for, since thinking using flatmap want joined set created recursively no stream created in first place. btw, i've tried -1000 level , still works quite fast , no problem.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -