java-如何使用toString方法轻松整齐地打印多个对象,这些对象也对齐?

前端之家收集整理的这篇文章主要介绍了java-如何使用toString方法轻松整齐地打印多个对象,这些对象也对齐? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个ArrayList成员,每个成员都有自己的信息,包括姓名,年龄,出生日期等,这些信息在打印到终端时用toString方法调用.

这是代码

@Override
    public String toString() {
        return "|ID: " + id + "| Name: " + name + "| Age: " + 
              calculateAge(age,LocalDate.now()) + "| Tlf.: " + tlfNo + "| Active: " + 
              activeMember + "| Next payment: " + nextPayment + "|";
    }

这是输出

|ID: 12| Name: Casper| Age: 49| Tlf.: 12345678| Active: true| Next payment: 2018-02-12|
|ID: 13| Name: Allan| Age: 69| Tlf.: 12345678| Active: true| Next payment: 2018-01-12|
|ID: 16| Name: Christina| Age: 100| Tlf.: 12345678| Active: false| Next payment: 2018-02-04|
|ID: 19| Name: RICK| Age: 49| Tlf.: 12345678| Active: false| Next payment: 2018-04-14|

如何获得不同的信息,使它们彼此对齐?

最佳答案
您可以为此创建一个方法,因为toString根本无法使用:

static String printPojos(Pojo... pojos) {
    int maxName = Arrays.stream(pojos)
                        .map(Pojo::getName)
                        .mapToInt(String::length)
                        .max()
                        .orElse(0);

    int maxId = Arrays.stream(pojos)
                      .mapToInt(x -> x.getName().length())
                      .max()
                      .orElse(0);

    StringJoiner result = new StringJoiner("\n");
    for (Pojo pojo : pojos) {
        StringJoiner sj = new StringJoiner("|");
        sj.add("ID: " + Strings.padEnd(Integer.toString(pojo.getId()),maxId,' '));
        sj.add(" Name: " + Strings.padEnd(pojo.getName(),maxName,' '));
        sj.add(" Age: " + Strings.padEnd(Integer.toString(pojo.getAge()),3,' '));
        sj.add(" Active: " + Strings.padEnd(Boolean.toString(pojo.isActive()),5,' '));

        result.merge(sj);
    }

    return result.toString();
}

我正在使用Strings :: padEnd(来自番石榴,但这即使没有外部库也很容易编写).

在我的情况下,Pojo看起来像这样:

static class Pojo {

    private final int id;
    private final String name;
    private final int age;
    private final boolean active;

    // constructor,getters

}

结果看起来像:

    Pojo one = new Pojo("Casper",49,true,1);
    Pojo two = new Pojo("Allan",100,10_000);

    System.out.println(printPojos(one,two));



ID: 1    | Name: Casper| Age: 49 | Active: true 
ID: 10000| Name: Allan | Age: 100| Active: true 
原文链接:https://www.f2er.com/java/532937.html

猜你在找的Java相关文章