Initialize map

This example will show how to initialize a java Map using core java and guava techniques.

Straight up Java

This snippet will show a standard way to initialize a empty HashMap JDK 5.0 and above.

@Test
public void create_new_map_java () {

    Map<String, String> newMap = new HashMap<String, String>();

    assertNotNull(newMap);
}

Diamond operator

Java 7 introduced the diamond operator which reduces java's verbosity on having to specify a generic type. The compiler will infer the parameter type based on the constructor's generic class. The snippet below will show how to initialize a Map using the diamond operator.

@Test
public void create_new_map_java_diamond_operator () {

    Map<String, String> newMap = new HashMap<>();

    assertNotNull(newMap);
}

Google Guava

Guava Maps.newHashMap will initialize and fill a Hashmap with elements if specified.

@Test
public void create_new_map_guava () {

    Map<String, String> newMap = Maps.newHashMap();

    assertNotNull(newMap);
}

Apache Commons

If you are looking to initialize an empty map this is an approach to take when using apache commons.

@Test
public void create_new_map_apache () {

    @SuppressWarnings("unchecked")
    Map<String, String> newMap = MapUtils.EMPTY_MAP;

    assertNotNull(newMap);
}