Computing the union of the keySets of two HashMaps in Java -
Computing the union of the keySets of two HashMaps in Java -
i want compute union of keys of 2 hashmaps. wrote next code (mwe below),
get unsupportedoperationexception. 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> sec = new hashmap<string, integer>(); first.put("first", 1); second.put("second", 2); set<string> 1 = first.keyset(); set<string> 2 = second.keyset(); set<string> union = one; union.addall(two); system.out.println(union); } }
so, union not copy of one, is one. is first.keyset(). , first.keyset() isn't re-create of keys of first, it's view, , won't back upwards adds, documented in map.keyset().
so need copy. simplest way write
1 = new hashset<string>(first); which uses "copy constructor" of hashset actual copy, instead of referring same object.
java hashmap set
Comments
Post a Comment