0

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.

rjoor
  • 3
  • 5
  • you may also want to look at [`Collectors.joining`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#joining-java.lang.CharSequence-java.lang.CharSequence-java.lang.CharSequence-) to create a string representation of a streamable – njzk2 Sep 25 '20 at 20:33

2 Answers2

1

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)

Turing85
  • 18,217
  • 7
  • 33
  • 58
0

I would just create another method like displayArrayPretty(ArrayList arr) where you loop through and print how you want. Ex.

for (String str: arr) {
System.out.println("- " + str);
}
Luke
  • 1
  • 4