15

I would like to instantiate Map<String, List<String>> in Java,

I tried

Map<String, List<String>> foo = new <String, List<String>>();

and

Map<String, List<String>> foo = new <String, ArrayList<String>>();

None of them work. Does any one know how to instantiate this map in Java?

jlordo
  • 37,490
  • 6
  • 58
  • 83
Alfred Zhong
  • 6,773
  • 11
  • 47
  • 59

3 Answers3

29
new HashMap<String, List<String>>();

or as gparyani commented:

new HashMap<>(); // type inference

Note: each entry needs to be given an instantiated List as a value. You cannot get("myKey").add("some_string_for_this_key"); the very first time you get() a List from it.

So, fetch a List, check if it's null.

If it's null, make a new list, add the string to it, put the List back. If it's anything but null, add to it, or do what you want.

Xabster
  • 3,710
  • 15
  • 21
16

You forgot to mention the class. Map here is the reference type and is an Interface. HashMap on the other side of equals specifies the actual type of the Object created and assigned to the reference foo.

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

The actual type specified (HashMap here) must be assignable to the reference type (Map here) i.e. if the type of reference is an Interface, the Object's type must implement it. And, if the type of the reference is a Class, the Object's type must either be the same class or its subtype i.e. it extends from it.

From Java 7 onwards, you can use a shorthand like

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

Your second way of instantiation is not recommended. Stick to using List which is an Interface.

// Don't bind your Map to ArrayList
new TreeMap<String, ArrayList<String>>();

// Use List interface type instead
new TreeMap<String, List<String>>();
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
6

Map is an interface. You have to tell Java which concrete Map class you want to instantiate.

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

or

Map<String, List<String>> foo = new TreeMap<String, List<String>>();

etc.

Willis Blackburn
  • 8,068
  • 19
  • 36