java - How to recursively flatMap a stream? -
this question has answer here:
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 stackoverflowexcepetion
if tree depth reaches ~10, can't accept. later developed implementation without recursion , stream (but brain roasted), i'm still wondering if there way recursive flatmap
s 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
Post a Comment