Home > Mobile >  How to add an entry into each Map stored in a List in a loop
How to add an entry into each Map stored in a List in a loop

Time:05-16

I have a list of maps List<Map<String,String>> with a name streams.

And it looks like this:

{
    "key1" : "value1",
    "key2" : "value2"
},
{
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
},
{
    "key1" : "value1",
    "key2" : "value2"
}

I do a loop on the map and want to add entry in specific condition this is my code:

public void addValue(String name, String value)
{
    for (Map<String,String> map :streams)
    {
        if (map.get("name").equals(name))
            map.put("newValue", value);
    }
}

I'm getting an exception:

java.lang.UnsupportedOperationException
    at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:71)
    at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:714)

I tried to write this:

public void addValue(String name, String value)
{
    for (Iterator<Map<String,String>> map :streams.iterator())
    {
        if (map.get("name").equals(name))
            map.put("newValue", value);
    }
}

But the compiler indicates an error on the row : streams.iterator() with the error:

Can only iterate over an array or an instance of java.lang.Iterable

How can I fix this?

CodePudding user response:

Since are getting UnsupportedOperationException maps in a list are unmodifiable.

You can fix the piece of code that creates these maps. If you are not in control of it, you can wrap each map in a list with map of required type (I mean HashMap, LinkedHashMap, TreeMap, etc.).

List<Map<String, String>> maps = new ArrayList<>();
for (Map<String, String> map : streams) 
    maps.add(new HashMap<>(map));
}

The attempt to use iterator is syntactically incorrect. Enhanced for loop (so-called "for-each" loop) can be used with objects that implement Iterable interface (not Iterator), like collections or Path. And enhanced for loop utilizes iterator under the hood, you don't need to create an iterator manually.

Anyway, the problem is rooted in the nature of your collections and not in the way how are iterating over the list.

  • Related