Skip to content

Instantly share code, notes, and snippets.

@daanta-real
Last active October 17, 2021 03:29
Show Gist options
  • Save daanta-real/4fedd381c98e351af84b99356713b545 to your computer and use it in GitHub Desktop.
Save daanta-real/4fedd381c98e351af84b99356713b545 to your computer and use it in GitHub Desktop.
Returns the single table map of String from 2-dimensions String array
// Returns the Table String from a String[][] data
public static String getTableStr (String[][] data) {
// Calculate the maximum lengths of the each columns
int[] len = new int[data[0].length];
Arrays.fill(len, 0);
for(String[] str: data) {
for(int i = 0; i < str.length; i++ ) {
String val = str[i];
int stringLen = val == null ? 0 : val.length();
if(stringLen > len[i]) len[i] = stringLen;
}
}
// StringBuilder Ready
StringBuilder sb = new StringBuilder();
// Render headers
String[] lis = data[0];
for(int i = 0; i < lis.length; i++) {
int printWidth = len[i] + 2;
String val = lis[i];
String printContent = String.format("%-" + printWidth + "s", val);
sb.append(printContent);
sb.append("\t");
}
sb.append('\n');
// Render ==== s
for(int i = 0; i < len.length; i++) {
int l = len[i];
sb.append(new String(new char[l]).replace("\0", "=")); // '='s
sb.append(new String(new char[2]).replace("\0", " ")); // spaces
sb.append("\t");
}
sb.append('\n');
// Render the contents
for(int i = 1; i < data.length; i++) {
String[] row = data[i];
for(int j = 0; j < row.length; j++) {
int printWidth = len[j] + 1;
String printContent = String.format("%-" + printWidth + "s", row[j]);
sb.append(printContent);
sb.append("\t");
}
sb.append('\n');
}
// Return the result
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment