javahashmapset

Computing the union of the keySets of two HashMaps in Java


I want to compute the union of the keys of two hashmaps. I wrote the following code (MWE below), but I

get UnsupportedOperationException. What would be a good of accomplishing this?

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class AddAll {

    public static void main(String args[]){

        Map<String, Integer> first = new HashMap<String, Integer>();
        Map<String, Integer> second = new HashMap<String, Integer>();

        first.put("First", 1);
        second.put("Second", 2);

        Set<String> one = first.keySet();
        Set<String> two = second.keySet();

        Set<String> union = one;
        union.addAll(two);

        System.out.println(union);


    }


}

Solution

  • So, union is not a copy of one, it is one. It is first.keySet(). And first.keySet() isn't a copy of the keys of first, it's a view, and won't support adds, as documented in Map.keySet().

    So you need to actually do a copy. The simplest way is probably to write

     one = new HashSet<String>(first);
    

    which uses the "copy constructor" of HashSet to do an actual copy, instead of just referring to the same object.