使用分隔每个条目的新行在toString中打印Arraylist

时间:2016-04-16 01:08:03

标签: java tostring

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

@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;
}

名单会打印,但所有条目都以括号和逗号存在于同一行。

我的教练坚持认为toString是自包含的,所以我在toString中的所有东西都必须留在那里。

名单打印如下:

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

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

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]

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

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

任何建议都将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:0)

将此代码用于名册:

... + roster.stream().collect(Collectors.joining("\n"))

答案 1 :(得分:0)

使用

roster.stream().collect(Collectors.joining("\n"))

String.join("\n", roster)

答案 2 :(得分:0)

所以,我想出了我的问题。我不得不删除return语句并将其放在最后,这样我就可以放入for-each循环并打印我的Arraylist。这是最终代码的样子:

@Override
public String toString() // Displays the info for a class
    {             

        System.out.print(getCourseId() + "\n" + getCourseName() + "\n" + getCourseCode()
            + "\n" + "\n" + "Instructor" + "\n" + "-------------------------" 
            + "\n" + Instructor.toString() + "\n" + "\n" + "Student Roster" 
            + "\n" + "-------------------------" + "\n");
                roster.stream().forEach((tmp) -> { // for each student, put 
                    System.out.println(tmp);       // them on a new line
    });

        return "";
    }