Skip to content

Instantly share code, notes, and snippets.

@konrad-garus
Created October 12, 2017 06:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save konrad-garus/bb87b6a01b2b6bdafca5566376dd0411 to your computer and use it in GitHub Desktop.
Save konrad-garus/bb87b6a01b2b6bdafca5566376dd0411 to your computer and use it in GitHub Desktop.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
public class Tree {
private int value;
private List<Tree> children = new LinkedList<>();
public Tree(int value, List<Tree> children) {
super();
this.value = value;
this.children.addAll(children);
}
public Tree(int value, Tree... children) {
this(value, asList(children));
}
public int getValue() {
return value;
}
public List<Tree> getChildren() {
return Collections.unmodifiableList(children);
}
public Stream<Tree> flattened() {
return Stream.concat(
Stream.of(this),
children.stream().flatMap(Tree::flattened));
}
public static void main(String[] args) {
Tree t = new Tree(15, new Tree(13), new Tree(124, new Tree(3), new Tree(4)));
// Get all values in the tree:
System.out.println("ALL VALUES: " + t.flattened().map(Tree::getValue).collect(toList()));
// Get even values:
System.out.println("EVEN VALUES: " + t.flattened().map(Tree::getValue).filter(v -> v % 2 == 0).collect(toList
()));
// Sum of even values:
System.out.println("SUM OF EVEN: " + t.flattened().map(Tree::getValue).filter(v -> v % 2 == 0).reduce((a, b)
-> a + b));
// Does it contain 13?
System.out.println("CONTAINS 13: " + t.flattened().anyMatch(n -> n.getValue() == 13));
}
}
// Prints:
// ALL VALUES: [15, 13, 124, 3, 4]
// EVEN VALUES: [124, 4]
// SUM OF EVEN: Optional[128]
// CONTAINS 13: true
@juanmf
Copy link

juanmf commented Apr 11, 2022

Nice! I needed print the tree nodes with indentation per level of the tree. A concept similar to poison pill pattern was very handy (adding marketNodes which only purpose is to be discarded but mark up and down levels):

        public Stream flattenedWithMarkers() {
            return Stream.concat(
                Stream.concat(
                    Stream.of(this, new LevelUpNode(null)),
                     childrenNodes.stream().flatMap(Node::flattenedWithMarkers))
                , Stream.of(new LevelDownNode(null)));

Client code would:

  IndentCounter cc ;
  if (node instanceof Node.LevelUpNode) {
      cc.incLevel();
  } else if (node instanceof Node.LevelDownNode) {
      cc.decLevel();
  } else {
      stringBuilder.append("   ".repeat(node.data, cc.level())));
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment