0

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.

Swayangjit
  • 1,875
  • 2
  • 13
  • 22
sankardev51
  • 37
  • 1
  • 6
  • seems that your `value` is instance of `UnmodifiableMap` so you cannot modify it with modification operations like `replaceAll` since it would alter the map. Check [this](https://stackoverflow.com/questions/8892350/immutable-vs-unmodifiable-collection) SO question. – Michał Krzywański Oct 14 '19 at 07:08
  • `Splitter` is not a standard Java class... maybe post its code or state which library it is from - if `Guava`, documentation is clear: "... returns an **unmodifiable** map ..." (but who cares to RFM) – user85421 Oct 14 '19 at 07:11

2 Answers2

1

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));
NiVeR
  • 9,644
  • 4
  • 30
  • 35
0

as @NiVeR said, com.google.common.base.Splitter.split() is returning a unmodifiable map.

You can copy the unmodifiable map into a modifiable map just before starting to modifying values.

For instance;

Map paramMap = Splitter.on(",").withKeyValueSeparator(":").split(lineitem);
paramMap = Maps.newHashMap(paramMap);
paramMap.replaceAll((key, value) -> value.replaceAll(";", ","));
Abdullah Gürsu
  • 3,010
  • 2
  • 17
  • 12