Created
November 15, 2012 19:02
-
-
Save collinvandyck/4080503 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Provides for nice formatting of tabular data. | |
| */ | |
| public class TextTable { | |
| private final List<Integer> maxWidths = Lists.newArrayList(); // widths for each column | |
| private final List<List<String>> rows = Lists.newArrayList(); | |
| public TextTable addRow(Iterable<? extends Object> items) { | |
| return addRow(Lists.newArrayList(items)); | |
| } | |
| public TextTable addRow(List<? extends Object> items) { | |
| final List<String> row = Lists.newArrayList(); | |
| rows.add(row); | |
| for (int col=0; col < items.size(); col++) { | |
| final String item = items.get(col).toString(); | |
| if (maxWidths.size() <= col) { | |
| maxWidths.add(item.length()); | |
| } else { | |
| int maxWidth = maxWidths.get(col); | |
| if (maxWidth < item.length()) { | |
| maxWidths.set(col, item.length()); | |
| } | |
| } | |
| row.add(item); | |
| } | |
| return this; | |
| } | |
| @Override | |
| public String toString() { | |
| final StringBuilder builder = new StringBuilder(); | |
| for (int rowIdx = 0; rowIdx < rows.size(); rowIdx++) { | |
| final List<String> row = rows.get(rowIdx); | |
| for (int colIdx = 0; colIdx < row.size(); colIdx++) { | |
| final String item = row.get(colIdx); | |
| builder.append(item); | |
| final int maxWidth = maxWidths.get(colIdx); | |
| for (int spacers=0; spacers < (maxWidth - item.length()); spacers ++) { | |
| builder.append(" "); | |
| } | |
| builder.append(" "); | |
| } | |
| builder.append("\n"); | |
| } | |
| return builder.toString(); | |
| } | |
| } |
Also, lines 34-35, can be replaced by
for (final List row : rows) {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hope you don't get angry on me giving opinions on your code (it's great, really), but just a small suggestion covering lines 38-43. :) As you are using Guava then why not use Strings.repeat(), isn't it?