Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a table of information in Java

I'm trying to print a table in Java and I was wondering what is the best way to do this?

I've tried printing new lines and using \t to make contents line up but it doesn't work. Is there a method which does this or a better way?

like image 578
user2704743 Avatar asked Sep 07 '13 11:09

user2704743


People also ask

Can you make tables in Java?

Java provides a useful class called JTable that enables you to create tables when developing graphical user interfaces using the components of Java's Swing API. You can enable your users to edit the data or just view it.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What does print () do in Java?

print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console.


2 Answers

This is one way to do it:

public class StoreItem {

    private String itemName;
    private double price;
    private int quantity;


    public StoreItem(String itemName, double price, int quantity) {
        this.setItemName(itemName);
        this.setPrice(price);
        this.setQuantity(quantity);
    }


    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }


    public static void printInvoiceHeader() {
        System.out.println(String.format("%30s %25s %10s %25s %10s", "Item", "|", "Price($)", "|", "Qty"));
        System.out.println(String.format("%s", "----------------------------------------------------------------------------------------------------------------"));
    }
    public void printInvoice() {
        System.out.println(String.format("%30s %25s %10.2f %25s %10s", this.getItemName(), "|", this.getPrice(), "|", this.getQuantity()));
    }

    public static List<StoreItem> buildInvoice() {
        List<StoreItem> itemList = new ArrayList<>();
        itemList.add(new StoreItem("Nestle Decaff Coffee", 759.99, 2));
        itemList.add(new StoreItem("Brown's Soft Tissue Paper", 15.80, 2));
        itemList.add(new StoreItem("LG 500Mb External Drive", 700.00, 2));
        return itemList;
    }

    public static void main (String[] args) {

        StoreItem.printInvoiceHeader();
        StoreItem.buildInvoice().forEach(StoreItem::printInvoice);
     }
}

Output:

enter image description here

like image 28
Ojonugwa Jude Ochalifu Avatar answered Sep 21 '22 10:09

Ojonugwa Jude Ochalifu


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    
like image 160
Vadim Zverev Avatar answered Sep 21 '22 10:09

Vadim Zverev