Skip to content

Instantly share code, notes, and snippets.

@PerWiklander
Created May 3, 2012 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PerWiklander/2588493 to your computer and use it in GitHub Desktop.
Save PerWiklander/2588493 to your computer and use it in GitHub Desktop.
String array column printer
package biz.wiklander.tools;
import java.util.Arrays;
public class StringArrayColumnPrinter {
public static void main(final String[] args) {
final String[] words = new String[] {
"one",
"duck",
"quacked",
"in",
"the",
"woods"
};
// "one", "duck", "quacked",
// "in", "the", "woods",
formatList(words, 3, false);
// "duck", "in", "one",
// "quacked", "the", "woods",
formatList(words, 3, true);
}
public static void formatList(
final String[] words,
final int wordsPerLine,
final boolean sort) {
if (sort) {
Arrays.sort(words);
}
final int[] charCount = new int[wordsPerLine];
int i = 0;
for (final String word : words) {
if (!(charCount[i % wordsPerLine] > word.length())) {
charCount[i % wordsPerLine] = word.length();
}
i++;
}
i = 0;
for (final String word : words) {
if (i % wordsPerLine == 0) {
System.out.print("\n");
}
System.out.print(
String.format(
"%1$-"
+ (charCount[i % wordsPerLine] + 4)
+ "s",
"\"" + word + "\", ")
);
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment