在打印的toString一个ArrayList与分隔每个输入行 [英] Printing an Arraylist in toString with lines separating each entry

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

问题描述

我有需要打印很多东西,包括其中包含多个条目的ArrayList一个toString。这些条目必须由新线分离。这里是的toString code,我与现在的工作:

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

任何建议将是极大的AP preciated。谢谢!

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天全站免登陆