Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list of key value objects

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!

like image 252
john cs Avatar asked Aug 24 '13 03:08

john cs


People also ask

How do you make a list of key value pairs?

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.

Can we have key-value in list?

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.


1 Answers

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);
like image 81
Juned Ahsan Avatar answered Sep 18 '22 00:09

Juned Ahsan