Thursday, May 18, 2017

KeySet And UnsupportedOperationException

package com.foo;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;

public class SomeTest {
 @Test
 public void test() {
 Map<String, Set<String>> movieToActorsName = new HashMap<>();
 Set<String> actors = new HashSet<>();
 actors.add("Dan");
 actors.add("Emma");
 movieToActorsName.put("HP", actors);
 Map<String, Set<String>> someMap = new HashMap<>();
 someMap.put("Movies", new HashSet<>(movieToActorsName.keySet()));
 someMap.values().stream().forEach(s -> {
 s.add("dummy");
 });
 someMap = new HashMap<>();
 someMap.put("Movies", movieToActorsName.keySet());
 someMap.values().stream().forEach(s -> {
 s.add("dummy"); // UnsupporrtedOperationException. Because keySet() is immutable.
 });
 }
}
Keyset is basically just a view of the keys in the map. So If you call remove() on the keyset, it will actually remove the entry for that key in the map.
I found this common where people directly take keySet of a map into a placeholder, which will be modified in the later part of the code. The following is wrong.
placeHolderMap.put(id, referenceMap.keySet());
And this is right.
placeHolderMap.put(id, new HashSet<>(referenceMap.keySet()));
or
placeHolderMap.put(id, referenceMap.keySet().stream().collect(Collectors.toSet()));

No comments:

Post a Comment