Search code examples
javaguava

Google Guava Maps vs Java Util Map


While checking out open source code, I many times encounter statements like

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

where Maps is of package com.google.common.collect.Maps (Google Guava)

Why can't we simply use the standard:

Map<String, List<String>> map = new HashMap<>();

instead?


Solution

  • The point here: before Java introduced the diamond operator, you had to repeat the generic type parameter when going for

    Map<Whatever> myMap = new HashMap<Whatever>() 
    

    The guava call allowed you to avoid repeating Whatever. In other words: this is nothing but a convenience method that isn't useful (and thus deprecated) since Java has the diamond operator. And its JavaDoc clearly explains that.

    newHashMap

    public static HashMap newHashMap()

    Note for Java 7 and later: this method is now unnecessary and should be treated as deprecated. Instead, use the HashMap constructor directly, taking advantage of the new "diamond" syntax.