A modern way would leave the manipulation of the string builder to a library method:
public String toString() {
return someListOfNumbers.stream()
.map(Number::toString)
.collect(Collectors.joining(" "));
}
I have assumed that someListOfNumbers
is a List<Long>
. My method doesn’t give the exact same result as yours: Your result has a leading space that I have left out. If you need that space, you may either prepend it yourself or use:
.collect(Collectors.joining(" ", " ", ""));
The three-arg joining
expects delimiter, prefix and suffix in the mentioned order (I am giving the empty string as suffix).
Side note: I had wanted to use .map(Long::toString)
, but it doesn’t compile because it is ambiguous. Here toString
may refer to either the no-arg Long.toString
or to the static one-arg Long.toString(long)
. I solved it referring to it via the superclass of Long
: Number::toString
. Another solution would be .map(String::valueOf)
as in Karol Dowbecki’s answer.