Skip to content

Instantly share code, notes, and snippets.

@cfstras
Created April 17, 2015 11:55
Show Gist options
  • Save cfstras/3c47282264a93daf4b9a to your computer and use it in GitHub Desktop.
Save cfstras/3c47282264a93daf4b9a to your computer and use it in GitHub Desktop.
Simple Tree-View with toString()
Root
+-- Flubber
| \-- Flabber
+-- Shoo
+-- Foo
| +-- Bar
| \-- Baz
\-- Fin
/**
* Assuming two methods are present:
* - List<SomeType> getChildren();
* - String() getName();
* Works for every tree structure.
*
* @return an ASCII-Tree of children
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(getName());
if (!getChildren().isEmpty()) {
b.append("\n");
for (int i=0; i<getChildren().size(); i++) {
String child = getChildren().get(i).toString();
if (i != getChildren().size()-1) {
b.append("+-- ");
b.append(child.replace("\n", "\n| "));
b.append("\n");
} else {
b.append("\\-- ");
b.append(child.replace("\n", "\n "));
}
}
}
return b.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment