Created
April 17, 2015 11:55
-
-
Save cfstras/3c47282264a93daf4b9a to your computer and use it in GitHub Desktop.
Simple Tree-View with toString()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Root | |
+-- Flubber | |
| \-- Flabber | |
+-- Shoo | |
+-- Foo | |
| +-- Bar | |
| \-- Baz | |
\-- Fin |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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