Thursday 25 May 2023

Java program to print table using formatter

In this post, I am going to demo an utility class to print the table data in left aligned, right aligned, left aligned in upper case and right aligned in upper case etc.,

 

I am using String.format method to format (for left and right alignments) the given column of the row.

 

Find the below working application.

 


StringTableUtils.java

package com.sample.app.strings;

import static java.lang.Math.max;
import static java.lang.String.format;

import java.util.List;

public class StringTableUtils {

	public static enum FormattingConstants {
		LEFT_ALIGN("%-{MAX_COLUMN_LENGTH}s"), RIGHT_ALIGN("%{MAX_COLUMN_LENGTH}s"),
		LEFT_ALIGN_CAPITAL_CASE("%-{MAX_COLUMN_LENGTH}S"), RIGHT_ALIGN_CAPITAL_CASE("%{MAX_COLUMN_LENGTH}S");

		private String val;

		FormattingConstants(String val) {
			this.val = val;
		}

		String formatString(int width) {
			return val.replace("{MAX_COLUMN_LENGTH}", "" + width);
		}
	}

	private StringTableUtils() {
	}

	private static int[] maxColumnLengths(List<List<String>> table) {
		final int tableWidth = table.get(0).size();
		int[] maxColumnLength = new int[tableWidth];
		for (List<String> row : table) {
			if (row.size() != tableWidth) {
				throw new IllegalArgumentException("Mismatch found in table widith. FirstRow size  = " + tableWidth
						+ ", current row size : " + row.size());
			}

			for (int i = 0; i < row.size(); i++) {
				maxColumnLength[i] = max(row.get(i).length(), maxColumnLength[i]);
			}
		}
		return maxColumnLength;
	}

	private static String[] formatStringsForTheColumn(List<List<String>> table, FormattingConstants alignment) {
		if (table.isEmpty()) {
			throw new IllegalArgumentException("Table is empty");
		}

		final int tableWidth = table.get(0).size();
		int maxColumnLengths[] = maxColumnLengths(table);
		String[] formatStrings = new String[tableWidth];
		for (int i = 0; i < tableWidth; i++) {
			formatStrings[i] = alignment.formatString(maxColumnLengths[i]);
		}
		return formatStrings;
	}

	public static String tableToString(List<List<String>> table, FormattingConstants alignment, char columnSeparator) {
		String[] formatStrings = formatStringsForTheColumn(table, alignment);

		StringBuilder builder = new StringBuilder();

		for (List<String> row : table) {
			for (int i = 0; i < row.size(); i++) {
				builder.append(columnSeparator);
				builder.append(format(formatStrings[i], row.get(i)));
			}
			builder.append(columnSeparator);
			builder.append("\n");
		}
		return builder.toString();
	}
}

StringTableUtilsDemo.java

package com.sample.app;

import static com.sample.app.strings.StringTableUtils.tableToString;

import java.util.Arrays;
import java.util.List;

import com.sample.app.strings.StringTableUtils.FormattingConstants;

public class StringTableUtilsDemo {
	public static void main(String[] args) {
		List<String> row1 = Arrays.asList("country", "capital", "Population");
		List<String> row2 = Arrays.asList("India", "New Delhi", "1,425,775,850");
		List<String> row3 = Arrays.asList("Canada", "Ottawa", "39,566,248");

		List<List<String>> table = Arrays.asList(row1, row2, row3);

		System.out.println("Left alignment table");
		System.out.println(tableToString(table, FormattingConstants.LEFT_ALIGN, '|'));

		System.out.println("\nRight alignment table");
		System.out.println(tableToString(table, FormattingConstants.RIGHT_ALIGN, '|'));

		System.out.println("\nLeft alignment & capital case table");
		System.out.println(tableToString(table, FormattingConstants.LEFT_ALIGN_CAPITAL_CASE, '|'));

		System.out.println("\nRight alignment & capital case table");
		System.out.println(tableToString(table, FormattingConstants.RIGHT_ALIGN_CAPITAL_CASE, '|'));
	}

}

Output

Left alignment table
|country|capital  |Population   |
|India  |New Delhi|1,425,775,850|
|Canada |Ottawa   |39,566,248   |


Right alignment table
|country|  capital|   Population|
|  India|New Delhi|1,425,775,850|
| Canada|   Ottawa|   39,566,248|


Left alignment & capital case table
|COUNTRY|CAPITAL  |POPULATION   |
|INDIA  |NEW DELHI|1,425,775,850|
|CANADA |OTTAWA   |39,566,248   |


Right alignment & capital case table
|COUNTRY|  CAPITAL|   POPULATION|
|  INDIA|NEW DELHI|1,425,775,850|
| CANADA|   OTTAWA|   39,566,248



Previous                                                 Next                                                 Home

No comments:

Post a Comment