fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. static class Tree<T> {
  12. List<Tree<T>> children = new ArrayList<>();
  13. T rootValue;
  14.  
  15. Tree(T rootValue) {
  16. this.rootValue = rootValue;
  17. }
  18.  
  19. Tree<T> add(Tree<T>... children) {
  20. this.children.addAll(Arrays.asList(children));
  21. return this;
  22. }
  23.  
  24. public String toIndentedString() {
  25. return "\n" + rootValue + children.stream()
  26. .map(Tree::toIndentedString)
  27. .map(s -> s.substring(0, s.length() - 1))
  28. .map(s -> s.replaceAll("\n", "\n "))
  29. .collect(Collectors.joining())
  30. + "\n";
  31. }
  32. }
  33.  
  34. public static void main(String[] args) {
  35. Tree<String> tree =
  36. new Tree<>("food")
  37. .add(new Tree<>("meat")
  38. .add(new Tree<>("fish")
  39. .add(new Tree<>("salmon"))
  40. .add(new Tree<>("cod"))
  41. .add(new Tree<>("tuna"))
  42. .add(new Tree<>("shark"))
  43. )
  44. )
  45. .add(new Tree<>("fruit"))
  46. .add(new Tree<>("vegetable"));
  47.  
  48. System.out.println("[" + tree.toIndentedString() + "]");
  49. }
  50. }
Success #stdin #stdout 0.13s 4386816KB
stdin
Standard input is empty
stdout
[
food
  meat
    fish
      salmon
      cod
      tuna
      shark
  fruit
  vegetable
]