How to convert a tree structure to a Stream of nodes in java

后端 未结 3 1072
甜味超标
甜味超标 2020-12-16 02:42

I want to convert a tree in a Java8 stream of nodes.

Here is a tree of nodes storing data which can be selected:

public class SelectTree {

           


        
3条回答
  •  甜味超标
    2020-12-16 03:18

    A more general approach using any node class is to add a parameter for the method, which returns the children:

    public class TreeNodeStream {
      public static  Stream of(T node, Function> childrenFunction) {
        return Stream.concat( //
          Stream.of(node), //
          childrenFunction.apply(node).stream().flatMap(n -> of(n, childrenFunction)));
      }
    }
    

    An example using File:

    TreeNodeStream.of(
      new File("."), f -> f.isDirectory() ? Arrays.asList(f.listFiles()) :
                                            Collections.emptySet())
      .filter(f -> f.getName().endsWith(".java"))
      .collect(Collectors::toList);
    

提交回复
热议问题