使用分隔每个条目的行在 toString 中打印 Arraylist [英] Printing an Arraylist in toString with lines separating each entry

查看:28
本文介绍了使用分隔每个条目的行在 toString 中打印 Arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 toString 需要打印很多东西,包括一个包含多个条目的 Arraylist.这些条目必须由一个新行分隔.这是我现在正在使用的 toString 代码:

I have a toString that needs to print a lot of stuff, including an Arraylist which contains multiple entries. Those entries have to be separated by a new line. Here is the toString code that I am working with right now:

@Override
public String toString() // Displays the info for a class
    {            
        return getCourseId() + "\n" + getCourseName() + "\n" + getCourseCode()
            + "\n" + "\n" + "Instructor" + "\n" + "-------------------------" 
            + "\n" + Instructor.toString() + "\n" + "\n" + "Student Roster" 
            + "\n" + "-------------------------" + "\n" + roster;
    }

名册确实会打印,但所有条目都在同一行中,并带有括号和逗号.

The roster does print, but all of the entries exist on the same line with brackets and commas.

我的导师坚持 toString 是独立的,所以我在 toString 中的所有内容目前都必须留在那里.

My instructor insists that the toString be self-contained, so everything that I have in the toString currently has to stay there.

花名册打印如下:

@Override
public String toString() // Displays the info for a person in order
    {
        return getPersonId() + "\t" + getLastName() + "\t" + getFirstName()
            + "\t" + getMajor() + "\t" + getGpa();
    }

目前,我得到的输出如下所示:

Currently, I get the output that looks like this:

10000
College Algebra
MATH 101

Instructor
-------------------------
X00009876   Jones   Jane    Associate Professor Mathematics

Student Roster
-------------------------
[X00000002  Smith   Sally   History         2.98, X00000003 Adams   Amanda     Civil Engineering    3.7, X00000005  Turner  Thomas  Nursing         2.34]

但我希望它看起来像这样:

But I would like it to look like this:

10000
College Algebra
MATH 101

Instructor
-------------------------
X00009876   Jones   Jane    Associate Professor Mathematics

Student Roster
-------------------------
X00000002   Smith   Sally   History         2.98
X00000003   Adams   Amanda     Civil Engineering    3.7
X00000005   Turner  Thomas  Nursing         2.34

任何建议将不胜感激.谢谢!

Any suggestions would be greatly appreciated. Thanks!

推荐答案

试试这个:

String rosterStr = roster.stream()
        .map(r -> r.toString())
        .collect(Collectors.joining("\n"))

哪个将获得花名册中每个值的字符串,然后用换行符将它们连接起来

Which will get the string for each value in roster, and then join them with newlines

这篇关于使用分隔每个条目的行在 toString 中打印 Arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆