Search code examples
javastringmapsreplaceall

Java 8 map.replaceAll method throws UnsupportedOperationException


I am trying to replace ";" with ","

Map<String, String> params =// Random method
params.replaceAll((key, value) -> value.replaceAll(";", ","));

Line 2 throws below exception.

java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.replaceAll(Collections.java:1510)

I am trying to replace any semicolons in the values with a comma.


Solution

  • You see it in the error that it says UnmodifiableMap. You are using an unmodifiable collection, meaning that it is read only once you created it.

    Looking at the source of the code it goes like:

    public Map<String, String> split(CharSequence sequence) {
      Map<String, String> map = new LinkedHashMap<String, String>();
      for (String entry : outerSplitter.split(sequence)) {
        Iterator<String> entryFields = entrySplitter.splittingIterator(entry);
    
        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
        String key = entryFields.next();
        checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
    
        checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
        String value = entryFields.next();
        map.put(key, value);
    
        checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
      }
      return Collections.unmodifiableMap(map);
    }
    

    You can notice that it returns Collections.unmodifiableMap(map).

    To make it modifiable you can simply create a new instance of a HashMap for example:

    Map paramMap = new HashMap<>(Splitter.on(",").withKeyValueSeparator(":").split(lineitem));