{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Quickly Declare and Initialise Lists, Maps and Arrays With Eclipse Templates

Java has a lot of boilerplate code, although each new version tries to remove a bit more every time. One area particularly affected is when you have to declare and initialise lists, maps or sets (some of it hopefully simplified in Java 7). Here’s some sample code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
Map<String, String> map = new HashMap<String, String>();
List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
String[] array = new String[] {};

To create any of these, you have to type a lot. Sometimes you make a mistake and have to retype. And half a minute later you’ve got one line of code that just declares a list. Also, you can have Eclipse automatically add imports when you save, but Eclipse normally can’t guess the correct List, instead prompting you to choose between java.util.List and java.awt.List (why isn’t there an option to use the former as the default?).

But Eclipse templates can help you avoid the hassle. Not only will it create the correct import statements, but also remove the effort of typing out the same type in the interface and implementation collection. If you’re new to templates, then see this tip to get an overview.

Import the templates automatically

Download the templates below then import them into Eclipse.

  • Declaration templates: This bundle includes:
    arraylist: A List declaration together with an ArrayList initialisation. Automatically imports the correct list (java.util.List).
    hashmap: A Map declaration together with a HashMap initialisation.
    hashset: A Set declaration together with a HashSet initialisation.
  • Initialisation templates: This bundle includes:
    An array declaration together with an array initialisation block.
    initlist: A List declaration together with an Arrays.asList() call for easy list initialisation.
    initmap: A Map declaration together with a call to Apache Commons Lang’s ArrayUtils.toMap() that makes light work of map initialisation. Commons Lang is sometimes already a dependency of external libraries so you may already be dependent on it, but this can extend to any other collection library (eg. Google Collections). You may get an unchecked warning because the method toMap() doesn’t use generics. I normally just add a @SuppressWarning(“unchecked).
From http://eclipseone.wordpress.com/2010/03/30/declare-initialise-lists-maps-arrays-with-eclipse-templates/
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks