Java Collections List Map toString

Java collections, like List and Map, are great. In fact they’re probably the most used part of the Java core APIs. They do lack one feature, though: easy to use conversion into a string representation. This is a surprisingly common task for error messages and logging. In neither of these cases is the default toString() sufficient.

Typical solutions include usage of a static utility class to convert them, iterating through them in your code, or creating a subclass of your own. None of these have ever made me happy, though. They’re either too verbose or clunky and the way I want to represent a collection as a string often varies considerably from one instantiation to another.

I had never thought about it before, but Java anonymous classes provide a great solution. You can simply specify a toString function when you create a collection by subclassing it anonymously.

Here’s a simple example. I have a class which contains a map. In logs and error messages I want to simply dump the keys.

public class MyClass {
  private Map map;

  public MyClass() {
      map = new HashMap<String, Stuff>() {
          public String toString() {
              String stringForm = new String();
              for(String key : this.keySet()) {
                  stringForm += key + ", ";
              }
              //remove the trailing ", "
              stringForm.substring(0, stringForm.length()-2);
              return stringForm;
          }
      };
  }
}

Later in my code I can simply run map.toString() to see a comma separated list of the keys in my map.

Of course, this pattern only helps when you need a flexible way to represent each collection as a String and when that collection is only created in one place. If you’re creating the collection in many methods a non-anonymous inner class may be a better fit.

0 Votes

Leave a comment

About this Entry

This page contains a single entry by Mike Nicholson published on November 3, 2009 1:50 PM.

Solairs PS Truncates Commands was the previous entry in this blog.

IntelliJ 8.1 Unresponsive on Mac is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.