![]() ![]() I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first's values being overwritten by the second's - in a single expression.Īssuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging. the contents of nested keys are simply overwritten, not merged I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. You can use an initializer in an anonymous subclass to make the syntax a little bit shorter: Map myMap = new HashMap() does not seem to handle nested dictionaries. ![]() No, you will have to add all the elements manually. (See also JEP 269 and the Javadoc) For up to Java Version 8: using mutableMap = new HashMap(Map.of("a", "b")) If you want the map to be mutable, you could copy it again, e.g. Note that in this case the resulting map will be an immutable map. The Map.of method is defined for up to ten elements in the map, while the Map.ofEntries method will have no such limit. Map multiValueMap new HashMap() multiValueMap.put(.In the example above both test and test2 will be the same, just with different ways of expressing the Map. this works for any number of elements: In Java 9 a couple of factory methods have been added that simplify the creation of maps : // this works for up to 10 elements: In case you happen to need just a single entry: There is Collections.singletonMap("key", "value").
0 Comments
Leave a Reply. |