Showing posts with label tostring. Show all posts
Showing posts with label tostring. Show all posts

December 31, 2014

Printing content of Java list

This is a very, very simple reference on how to print the contents of a Java List.  The idea is simple. I have a List and I want to loop over it and print whatever is stored in it. But do you really need to code a loop to do this?  Nope.  But I always forget how to correctly do it.  So here it is:

List< String > strings = new LinkedList< String >();
strings.add("one");
strings.add("two");
strings.add("three");

System.out.printf(
 "List< String >.toString()\n%s\n\n"
 ,strings.toString());
System.out.printf(
 "List< String >.toArray().toString()\n%s\n\n"
 ,strings.toArray().toString());
System.out.printf(
 "Arrays.toString(List< String >.toArray())\n%s\n\n"
 ,Arrays.toString(strings.toArray()));

The output looks like this:
List< String >.toString()
[one, two, three]

List< String >.toArray().toString()
[Ljava.lang.Object;@1ea87e7b

Arrays.toString(List< String >.toArray())
[one, two, three] 


Enjoy!