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

时间:2019-05-07 09:02:42

标签: java layout 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|

我如何获取不同的信息以彼此对齐?

3 个答案:

答案 0 :(得分:1)

您可以为此创建一个方法,因为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(来自guava,但这即使没有外部库也很容易编写)。

在我的情况下,

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, true, 10_000);

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



ID: 1    | Name: Casper| Age: 49 | Active: true 
ID: 10000| Name: Allan | Age: 100| Active: true 

答案 1 :(得分:1)

您可以执行以下操作:

 public String toString() {
        return String.format("|id: %10d |Name: %30s| Age: %02d | Tlf.: %d| Active: %s| Next Payment: %s |", id, getNameTrimmed() , age , tlfNo ,    activeMember, nextPayment );
 }

 private  String getNameTrimmed(){
    if(name.length()>30) {
        return name.substring(0,27)+"...";
    }
    return name;
}

这样,ID将有10个字符(如果您的ID较长,则ID仍会破坏格式) 名称将有30个字符,因此您需要添加一个方法来给您30个字符的名称

答案 2 :(得分:0)

对于您的问题,我有一个简单的实现,不需要外部库。如果要使用外部库,则可以在Apache-commons或Guava中找到足够的方法。可能可以做得更聪明,但这可以解决问题:

class Member {

  String id;
  String name;
  int age;
  LocalDate date;
  int tlfNo;
  boolean activeMember;
  LocalDate nextPayment;

  public Member(String id, String name, int age, int tlfNo, boolean activeMember, LocalDate nextPayment) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.tlfNo = tlfNo;
    this.activeMember = activeMember;
    this.nextPayment = nextPayment;
  }

  @Override
  public String toString() {
    return String.format("|ID: %s| Name: %s| Age: %s| Tlf.: %s| Active: %s| Next payment: %s|", 
      doFormat(id, "id", 10), doFormat(name, "name", 10),             
      doFormat(String.valueOf(age), "age", 10), 
      doFormat(String.valueOf(tlfNo), "tlfNo", 10), 
      doFormat(String.valueOf(activeMember), "active", 10),             
      doFormat(nextPayment.toString(), "nextPayment", 20));
  }

  String doFormat(String value, String fieldName, int maxLenght) {
    if (value.length() > maxLenght) {
      throw new IllegalArgumentException(String.format("cannot format string longer than %s for %s, value = %s", maxLenght, fieldName, value));
    }
    return padLeftSpaces(value, maxLenght);
  }

  public String padtLefSpaces(String inputString, int length) {
    if (inputString.length() >= length) {
      return inputString;
    }
    StringBuilder sb = new StringBuilder();
    while (sb.length() < length - inputString.length()) {
      sb.append(' ');
    }
    sb.append(inputString);

    return sb.toString();
  }
}

这个想法是您用空格填充所有字段,并且仅替换已占用的空间。左移填充方法是从bealdung

借用的