Printing Java Collections Nicely (toString Doesn't Return Pretty Output) Printing Java Collections Nicely (toString Doesn't Return Pretty Output) java java

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)


You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));


String.join(",", yourIterable);

(Java 8)


With java 8 streams and collectors it can be done easily:

String format(Collection<?> c) {  String s = c.stream().map(Object::toString).collect(Collectors.joining(","));  return String.format("[%s]", s);}

first we use map with Object::toString to create Collection<String> and then use joining collector to join every item in collection with , as delimiter.