I am trying to create a list of key-value pairs. Here is what I have so far:
Map<Integer,String> map = new HashMap<Integer,String>().put(songID, songList.get(i).name);
This gives me the following error:
Type mismatch: cannot convert from String to Map
Also, how would I iterate through these? Thanks!
Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as. list(). Basically what we will have here is a syntax like given below, which will create a list and assign all the keys with their respective values.
A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair. A key in the key-value pair must be immutable.
When you call put
on the map of type Map <Integer,String>
, you will get the String returned. So when you do this:
new HashMap<Integer,String>().put(songID, songList.get(i).name);
it will return a String
and when you try to assign it to a map
Map<Integer,String> map
compiler throws an error,
Type mismatch: cannot convert from String to Map
Here is the signature of put method form javadocs:
public V put(K key,
V value)
you need to break down the this complex problematic statement:
Map<Integer,String> map = new HashMap<Integer,String>().put(songID, songList.get(i).name);
to something like:
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(songID, songList.get(i).name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With