How to instantiate a map <String, List <String>> in Java
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 anyone know how to instantiate this map in Java?
new HashMap<String, List<String>>(); or, as gparyani commented:
new HashMap<>(); // type inference Note. Each entry must be assigned an instance of List as a value. You cannot receive ("myKey"). Add ("some_string_for_this_key"); the first time you get () a list of it.
So, select List, check if it is null.
If it is null, create a new list, add a line to it, return the list. If it's nothing but zero, add to it or do what you want.
You forgot to mention the class. Map here is a reference type and is an interface. HashMap on the other hand of equals indicates the actual type of object created and assigned to the foo reference.
Map<String, List<String>> foo = new HashMap<String, List<String>>(); The actual type specified here ( HashMap here) must be assigned for the reference type ( Map here), that is, if the type of the link is an interface, the type of the object must implement it. And, if the type of reference is a class, the type of the object must either be the same class or its subtype, that is, it leaves it.
Starting with Java 7, you can use the short name
Map<String, List<String>> foo = new HashMap<>(); The second method of creation is not recommended . Use 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>>(); A map is an interface. You must tell Java which particular map class you want to create.
Map<String, List<String>> foo = new HashMap<String, List<String>>(); or
Map<String, List<String>> foo = new TreeMap<String, List<String>>(); and etc.