Skip to content
Advertisement

How should I go about printing all elements in an ArrayList via a toString in a formatted manner?

What I am asking is that, in Java 8, when I call my toString() method (overridden), I am trying to print out the elements of each respective ArrayList<String> in this manner:

- str1
- str2
- str3

But instead, when I return the ArrayList<String>, it is printed in this manner:

[str1, str2, str3]

It makes perfect sense to me why it is printed that way, but I’m not sure how I would go about changing how it is displayed in the toString(). Note that this ArrayList<String> varies in size depending on the object of which it is apart of, and I would rather not use an external method to print these elements out in such a manner unless there was no other way to do it.

Furthermore, I don’t think it even makes sense to have a for loop within a toString() printing out the elements of the ArrayList<String> in the aforementioned manner, and I don’t think Java would allow that anyway.

Advertisement

Answer

One solution would be to write a custom List-implementation to wrap a list in and then override toString(). This seems pretty overkill. Instead, I suggest printing the entries of the List with the help of the Stream API:

list.forEach(entry -> System.out.println("- " + entry));

Ideone demo

With the advent of the new instance method String::formatted (currently a preview feature), we could also write

list.stream()
    .map("- %s"::formatted)
    .forEach(System.out::println);

(Sorry, no Ideone demo for this one, Ideone runs on Java 12)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement