使用StringBuilder的漂亮表

使用StringBuilder的漂亮表,第1张

使用StringBuilder的漂亮表

当然,一种简单的方法是创建硬连接的

printf
语句。但是,这不是非常灵活,因为您始终必须固定列宽,并且功能将始终特定于一个类及其字段。

因此,我想提出一个辅助类,主要做两件事:

  • 封装表单元条目的创建(通过Java 8
    Function
  • 计算给定元素集的每个columnm的最大宽度。

假设有一个给定的模型类,例如

Person
,例如:

class Person{    int getId() { ... }    String getFirstName() { ... }    String getLastName() { ... }    float getHeight()  { ... }}

然后,我要创建一个“ nice”表,如下所示:

TableStringBuilder<Person> t = new TableStringBuilder<Person>();t.addColumn("id", Person::getId);t.addColumn("first name", Person::getFirstName);t.addColumn("last name", Person::getLastName);t.addColumn("height", Person::getHeight);String s = t.createString(persons);

我希望此字符串的内容是格式正确的表:

   id|   first name|    last name|height-----+-------------+-------------+------41360|Xvnjhpdqdxvcr|    Stvybcwvm|   1.7 3503|      Krxvzxk|      Xtspsjd|   1.641198|       Uegqfl|  Qlocfljbepo|  1.5826517|       Somyar|       Aopufo|  1.7713773| Dxehxjbhwgsm|     Jgnlonjv|  1.7713067|       Zozitk|       Jbozwd|  1.8146534|        Bosyq|      Kcprrdc|  1.5593862|    Rlfxblgqp|   Pgrntaqoos|  1.8512155|   Kjpjlavsqc|Rxfrrollhwhoh|  1.7975712|        Fwpnd|     Mwcsshwx|  1.78

这是显示这样的MVCE

TableStringBuilder
及其应用的MVCE:

import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.function.Function;public class TableStringTest{    public static void main(String[] args)    {        List<Person> persons = new ArrayList<Person>();        for (int i=0; i<10; i++)        { persons.add(new Person());        }        TableStringBuilder<Person> t = new TableStringBuilder<Person>();        t.addColumn("id", Person::getId);        t.addColumn("first name", Person::getFirstName);        t.addColumn("last name", Person::getLastName);        t.addColumn("height", Person::getHeight);        String s = t.createString(persons);        System.out.println(s);    }}class TableStringBuilder<T>{    private final List<String> columnNames;    private final List<Function<? super T, String>> stringFunctions;    TableStringBuilder()    {        columnNames = new ArrayList<String>();        stringFunctions = new ArrayList<Function<? super T, String>>();    }    void addColumn(String columnName, Function<? super T, ?> fieldFunction)    {        columnNames.add(columnName);        stringFunctions.add((p) -> (String.valueOf(fieldFunction.apply(p))));    }    private int computeMaxWidth(int column, Iterable<? extends T> elements)    {        int n = columnNames.get(column).length();        Function<? super T, String> f = stringFunctions.get(column);        for (T element : elements)        { String s = f.apply(element); n = Math.max(n, s.length());        }        return n;    }    private static String padLeft(String s, char c, int length)    {        while (s.length() < length)        { s = c + s;        }        return s;    }    private List<Integer> computeColumnWidths(Iterable<? extends T> elements)    {        List<Integer> columnWidths = new ArrayList<Integer>();        for (int c=0; c<columnNames.size(); c++)        { int maxWidth = computeMaxWidth(c, elements); columnWidths.add(maxWidth);        }        return columnWidths;    }    public String createString(Iterable<? extends T> elements)    {        List<Integer> columnWidths = computeColumnWidths(elements);        StringBuilder sb = new StringBuilder();        for (int c=0; c<columnNames.size(); c++)        { if (c > 0) {     sb.append("|"); } String format = "%"+columnWidths.get(c)+"s"; sb.append(String.format(format, columnNames.get(c)));        }        sb.append("n");        for (int c=0; c<columnNames.size(); c++)        { if (c > 0) {     sb.append("+"); } sb.append(padLeft("", '-', columnWidths.get(c)));        }        sb.append("n");        for (T element : elements)        { for (int c=0; c<columnNames.size(); c++) {     if (c > 0)     {         sb.append("|");     }     String format = "%"+columnWidths.get(c)+"s";     Function<? super T, String> f = stringFunctions.get(c);     String s = f.apply(element);     sb.append(String.format(format, s)); } sb.append("n");        }        return sb.toString();    }}//Dummy Person Classclass Person{    private int id;    private String firstName;    private String lastName;    private float height;    private static Random random = new Random(0);    Person()    {        id = random.nextInt(100000);        firstName = createRandomString();        lastName = createRandomString();        height = (150 + random.nextInt(40)) / 100.0f;    }    private static String createRandomString()    {        int length = random.nextInt(10) + 5;        StringBuilder sb = new StringBuilder();        char offset = 'A';        for (int i=0; i<length; i++)        { char c = (char)(random.nextInt(26) + offset); sb.append(c); offset = 'a';        }        return sb.toString();    }    int getId()    {        return id;    }    String getFirstName()    {        return firstName;    }    String getLastName()    {        return lastName;    }    float getHeight()    {        return height;    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5133449.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存