user2939293
user2939293

Reputation: 813

Add values to List<Map<String, String>>

I have a problem with my java code that I hope someone can help me with.

I need help adding values to a list of type List<Map<String, String>>.

I try with myList.add(map.put(value1, value2)), but that's wrong.

List<Map<String, String>> myList = null;
Map<String, String> map = null;

for (int i=0; i<daysList.getLenght(); i++)
{
    myList.add(map.put(value1, value2));  //This line is not working
}

Upvotes: 0

Views: 12848

Answers (4)

Yusuf K.
Yusuf K.

Reputation: 4250

You can't do that way. Try someting like that

List<Map<String, String>> myList = null;
Map<String, String> map = null;

for (int i=0; i<daysList.getLenght(); i++)
{

    map.put(value1, value2) //map is null so this line will throw NullPointerException
    myList.add(map);  //Also mylist is null if you fix map null problem another NullPointerException is thrown here
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 311188

You need to create an instance of a class that implements the Map interface (e.g., a HashMap<>) to place in the list:

for (int i = 0; i < daysList.getLenght(); i++) {
    Map<String, String> map = new HashMap<>();
    map.put(value1, value2)
    myList.add(map);
}

Upvotes: 1

nits.kk
nits.kk

Reputation: 5316

You need to change the code as below

for (int i=0; i<daysList.getLength(); i++){
    Map<String, String> map = new HashMap<String,String>();
    map.put(value1, value2);
    myList.add(map);  
}

Method put() from Map.java returns

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

Your List needs Map object but you are providing the previous value associated with the key which is not of type Map.

Upvotes: 1

blacktide
blacktide

Reputation: 12076

The Map#put method doesn't return the map, it returns the previous value associated with key, or null if there was no mapping for key.

If you want to add the map to the list, you'll need to do something like this:

map.put(value1, value2);
myList.add(map);

Upvotes: 2

Related Questions