How to print a table of information in Java
You can use System.out.format(...)
Example:
final Object[][] table = new String[4][];
table[0] = new String[] { "foo", "bar", "baz" };
table[1] = new String[] { "bar2", "foo2", "baz2" };
table[2] = new String[] { "baz3", "bar3", "foo3" };
table[3] = new String[] { "foo4", "bar4", "baz4" };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s%n", row);
}
Result:
foo bar baz
bar2 foo2 baz2
baz3 bar3 foo3
foo4 bar4 baz4
Or use the following code for left-aligned output:
System.out.format("%-15s%-15s%-15s%n", row);
General function to table-format a list of arrays:
public static String formatAsTable(List<List<String>> rows)
{
int[] maxLengths = new int[rows.get(0).size()];
for (List<String> row : rows)
{
for (int i = 0; i < row.size(); i++)
{
maxLengths[i] = Math.max(maxLengths[i], row.get(i).length());
}
}
StringBuilder formatBuilder = new StringBuilder();
for (int maxLength : maxLengths)
{
formatBuilder.append("%-").append(maxLength + 2).append("s");
}
String format = formatBuilder.toString();
StringBuilder result = new StringBuilder();
for (List<String> row : rows)
{
result.append(String.format(format, row.toArray(new String[0]))).append("\n");
}
return result.toString();
}
Usage:
List<List<String>> rows = new ArrayList<>();
List<String> headers = Arrays.asList("Database", "Maintainer", "First public release date", "Latest stable version", "Latest release date");
rows.add(headers);
rows.add(Arrays.asList("4D (4th Dimension)", "4D S.A.S.", "1984", "v16.0", "2017-01-10"));
rows.add(Arrays.asList("ADABAS", "Software AG", "1970", "8.1", "2013-06"));
rows.add(Arrays.asList("Adaptive Server Enterprise", "SAP AG", "1987", "16.0", "2015"));
rows.add(Arrays.asList("Apache Derby", "Apache", "2004", "10.14.1.0", "2017-10-22"));
System.out.println(formatAsTable(rows));
The result:
Database Maintainer First public release date Latest stable version Latest release date
4D (4th Dimension) 4D S.A.S. 1984 v16.0 2017-01-10
ADABAS Software AG 1970 8.1 2013-06
Adaptive Server Enterprise SAP AG 1987 16.0 2015
Apache Derby Apache 2004 10.14.1.0 2017-10-22