Less Verbose Java Collection Creation With Google Guava

Creating generic collections in Java is very verbose. Sometimes it may be hard to fit in one line:

Map<Integer, List<ClassWithLongName>> mapping
    = new HashMap<Integer, List<ClassWithLongName>>();

It can be shortened with a static factory method. Following the advice from Effective Java by Joshua Bloch some time ago I created a simple collection factory:

public class CollectionFactory {

    public static <K, V> HashMap<K, V> newHashMap() {
        return new HashMap<K, V>();
    }

    public static <T> List<T> newArrayList() {
        return new ArrayList<T>();
    }

    public static <T> Set<T> newHashSet() {
        return new HashSet<T>();
    }
}

After importing the newHashMap method statically, the declaration from the first listing can be shortened like this:

Map<Integer, List<ClassWithLongName>> mapping = newHashMap();

Such static factory methods are available in Google Guava library, a successor to Google Collections. Instead of your own method you can use Maps.newHashMap from com.google.common.collect package. There are also methods for creating other collection types and with additional parameters like initial capacity. See API documentation for the following classes in com.google.common.collect package:

  • Lists
  • Sets
  • Maps
Share
This entry was posted in Java and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>