用 Java 漂亮地打印二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11383070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:51:37  来源:igfitidea点击:

Pretty print 2D array in Java

java

提问by DD.

I'm looking for a util which will print a rectangular String[][] into a human-readable table with correct column lengths.

我正在寻找一个实用程序,它将一个矩形 String[][] 打印到一个具有正确列长度的人类可读表中。

回答by Lyubomyr Shaydariv

If you want something similar to MySQL command-line client output, you can use something like that:

如果您想要类似于 MySQL 命令行客户端输出的内容,您可以使用以下内容:

import java.io.PrintStream;

import static java.lang.String.format;
import static java.lang.System.out;

public final class PrettyPrinter {

    private static final char BORDER_KNOT = '+';
    private static final char HORIZONTAL_BORDER = '-';
    private static final char VERTICAL_BORDER = '|';

    private static final String DEFAULT_AS_NULL = "(NULL)";

    private final PrintStream out;
    private final String asNull;

    public PrettyPrinter(PrintStream out) {
        this(out, DEFAULT_AS_NULL);
    }

    public PrettyPrinter(PrintStream out, String asNull) {
        if ( out == null ) {
            throw new IllegalArgumentException("No print stream provided");
        }
        if ( asNull == null ) {
            throw new IllegalArgumentException("No NULL-value placeholder provided");
        }
        this.out = out;
        this.asNull = asNull;
    }

    public void print(String[][] table) {
        if ( table == null ) {
            throw new IllegalArgumentException("No tabular data provided");
        }
        if ( table.length == 0 ) {
            return;
        }
        final int[] widths = new int[getMaxColumns(table)];
        adjustColumnWidths(table, widths);
        printPreparedTable(table, widths, getHorizontalBorder(widths));
    }

    private void printPreparedTable(String[][] table, int widths[], String horizontalBorder) {
        final int lineLength = horizontalBorder.length();
        out.println(horizontalBorder);
        for ( final String[] row : table ) {
            if ( row != null ) {
                out.println(getRow(row, widths, lineLength));
                out.println(horizontalBorder);
            }
        }
    }

    private String getRow(String[] row, int[] widths, int lineLength) {
        final StringBuilder builder = new StringBuilder(lineLength).append(VERTICAL_BORDER);
        final int maxWidths = widths.length;
        for ( int i = 0; i < maxWidths; i++ ) {
            builder.append(padRight(getCellValue(safeGet(row, i, null)), widths[i])).append(VERTICAL_BORDER);
        }
        return builder.toString();
    }

    private String getHorizontalBorder(int[] widths) {
        final StringBuilder builder = new StringBuilder(256);
        builder.append(BORDER_KNOT);
        for ( final int w : widths ) {
            for ( int i = 0; i < w; i++ ) {
                builder.append(HORIZONTAL_BORDER);
            }
            builder.append(BORDER_KNOT);
        }
        return builder.toString();
    }

    private int getMaxColumns(String[][] rows) {
        int max = 0;
        for ( final String[] row : rows ) {
            if ( row != null && row.length > max ) {
                max = row.length;
            }
        }
        return max;
    }

    private void adjustColumnWidths(String[][] rows, int[] widths) {
        for ( final String[] row : rows ) {
            if ( row != null ) {
                for ( int c = 0; c < widths.length; c++ ) {
                    final String cv = getCellValue(safeGet(row, c, asNull));
                    final int l = cv.length();
                    if ( widths[c] < l ) {
                        widths[c] = l;
                    }
                }
            }
        }
    }

    private static String padRight(String s, int n) {
        return format("%1$-" + n + "s", s);
    }

    private static String safeGet(String[] array, int index, String defaultValue) {
        return index < array.length ? array[index] : defaultValue;
    }

    private String getCellValue(Object value) {
        return value == null ? asNull : value.toString();
    }

}

And use it like that:

并像这样使用它:

final PrettyPrinter printer = new PrettyPrinter(out);
printer.print(new String[][] {
        new String[] {"FIRST NAME", "LAST NAME", "DATE OF BIRTH", "NOTES"},
        new String[] {"Joe", "Smith", "November 2, 1972"},
        null,
        new String[] {"John", "Doe", "April 29, 1970", "Big Brother"},
        new String[] {"Hyman", null, null, "(yes, no last name)"},
});

The code above will produce the following output:

上面的代码将产生以下输出:

+----------+---------+----------------+-------------------+
|FIRST NAME|LAST NAME|DATE OF BIRTH   |NOTES              |
+----------+---------+----------------+-------------------+
|Joe       |Smith    |November 2, 1972|(NULL)             |
+----------+---------+----------------+-------------------+
|John      |Doe      |April 29, 1970  |Big Brother        |
+----------+---------+----------------+-------------------+
|Hyman      |(NULL)   |(NULL)          |(yes, no last name)|
+----------+---------+----------------+-------------------+

回答by lilroo

I dont know about a util library that would do this but you can use the String.format function to format the Strings as you want to display them. This is an example i quickly wrote up:

我不知道可以执行此操作的 util 库,但是您可以使用 String.format 函数来设置您想要显示的字符串格式。这是我很快写的一个例子:

String[][] table = {{"Joe", "Bloggs", "18"},
        {"Steve", "Jobs", "20"},
        {"George", "Cloggs", "21"}};

    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++){
            System.out.print(String.format("%20s", table[i][j]));
        }
        System.out.println("");
    }

This give the following output:

这给出了以下输出:

            Joe               Bloggs                  18
          Steve               Jobs                    20
         George               Cloggs                  21

回答by fvu

You can try

你可以试试

System.out.println(Arrays.deepToString(someRectangularStringArray));

And that's as pretty as it'll get without specific code.

这与没有特定代码的情况一样漂亮。

回答by Shadi Moadad

JakWharton has a nice solution https://github.com/JakeWharton/flip-tablesand format String[], List of objects with reflection on property name and result sets. e.g.

JakWharton 有一个很好的解决方案https://github.com/JakeWharton/flip-tables和格式 String[],具有属性名称和结果集反射的对象列表。例如

List<Person> people = Arrays.asList(new Person("Foo", "Bar"), new Person("Kit", "Kat"));
System.out.println(FlipTableConverters.fromIterable(people, Person.class));

回答by Sebastian van Wickern

Since I stumbled upon this searching for a ready to use printer (but not only for Strings) I changed Lyubomyr Shaydariv's code written for the accepted answera bit. Since this probably adds value to the question, I'll share it:

由于我偶然发现了一个现成的打印机(但不仅限于字符串),因此我稍微更改了Lyubomyr Shaydariv接受的答案编写的代码。由于这可能为问题增加了价值,我将分享它:

import static java.lang.String.format;

public final class PrettyPrinter {

    private static final char BORDER_KNOT = '+';
    private static final char HORIZONTAL_BORDER = '-';
    private static final char VERTICAL_BORDER = '|';

    private static final Printer<Object> DEFAULT = new Printer<Object>() {
        @Override
        public String print(Object obj) {
            return obj.toString();
        }
    };

    private static final String DEFAULT_AS_NULL = "(NULL)";

    public static String print(Object[][] table) {
        return print(table, DEFAULT);
    }

    public static <T> String print(T[][] table, Printer<T> printer) {
        if ( table == null ) {
            throw new IllegalArgumentException("No tabular data provided");
        }
        if ( table.length == 0 ) {
            return "";
        }
        if( printer == null ) {
        throw new IllegalArgumentException("No instance of Printer provided");
        }
        final int[] widths = new int[getMaxColumns(table)];
        adjustColumnWidths(table, widths, printer);
        return printPreparedTable(table, widths, getHorizontalBorder(widths), printer);
    }

    private static <T> String printPreparedTable(T[][] table, int widths[], String horizontalBorder, Printer<T> printer) {
        final int lineLength = horizontalBorder.length();
        StringBuilder sb = new StringBuilder();
        sb.append(horizontalBorder);
        sb.append('\n');
        for ( final T[] row : table ) {
            if ( row != null ) {
                sb.append(getRow(row, widths, lineLength, printer));
                sb.append('\n');
                sb.append(horizontalBorder);
                sb.append('\n');
            }
        }
        return sb.toString();
    }

    private static <T> String getRow(T[] row, int[] widths, int lineLength, Printer<T> printer) {
        final StringBuilder builder = new StringBuilder(lineLength).append(VERTICAL_BORDER);
        final int maxWidths = widths.length;
        for ( int i = 0; i < maxWidths; i++ ) {
            builder.append(padRight(getCellValue(safeGet(row, i, printer), printer), widths[i])).append(VERTICAL_BORDER);
        }
        return builder.toString();
    }

    private static String getHorizontalBorder(int[] widths) {
        final StringBuilder builder = new StringBuilder(256);
        builder.append(BORDER_KNOT);
        for ( final int w : widths ) {
            for ( int i = 0; i < w; i++ ) {
                builder.append(HORIZONTAL_BORDER);
            }
            builder.append(BORDER_KNOT);
        }
        return builder.toString();
    }

    private static int getMaxColumns(Object[][] rows) {
        int max = 0;
        for ( final Object[] row : rows ) {
            if ( row != null && row.length > max ) {
                max = row.length;
            }
        }
        return max;
    }

    private static <T> void adjustColumnWidths(T[][] rows, int[] widths, Printer<T> printer) {
        for ( final T[] row : rows ) {
            if ( row != null ) {
                for ( int c = 0; c < widths.length; c++ ) {
                    final String cv = getCellValue(safeGet(row, c, printer), printer);
                    final int l = cv.length();
                    if ( widths[c] < l ) {
                        widths[c] = l;
                    }
                }
            }
        }
    }

    private static <T> String padRight(String s, int n) {
        return format("%1$-" + n + "s", s);
    }

    private static <T> T safeGet(T[] array, int index, Printer<T> printer) {
        return index < array.length ? array[index] : null;
    }

    private static <T> String getCellValue(T value, Printer<T> printer) {
        return value == null ? DEFAULT_AS_NULL : printer.print(value);
    }

}

And Printer.java:

和 Printer.java:

public interface Printer<T> {
    String print(T obj);
}

Usage:

用法:

    System.out.println(PrettyPrinter.print(some2dArray, new Printer<Integer>() {
        @Override
        public String print(Integer obj) {
            return obj.toString();
        }
    }));

Why the change to T? Well Stringwas not enough, but I don't always want the same output obj.toString()has to offer, so I used the interface to be able to change that at will.

为什么改为T? 好String是不够的,但我不希望总是相同的输出obj.toString()所提供的,所以我用的接口,以便能够改变这种随意。

The second change is not providing the class with an outstream, well if you want to use the class with a Logger like (Log4j // Logback) you will definitly have a problem using streams.

第二个变化是没有为类提供outstream,如果你想将类与像 (Log4j // Logback) 这样的 Logger 一起使用,你肯定会在使用流时遇到问题。

Why the change to only support static calls? I wanted to use it for loggers, and making just one single call seemed the obvious choice.

为什么改为只支持静态调用?我想将它用于记录器,并且只进行一次调用似乎是显而易见的选择。