Java – can I add keys / values to a map in a map in one line of code?
•
Java
I have HashMap 1, which contains five keys. All keys have hashmaps as the value I want to add key / value pairs to these sub maps
map1.get(subCategoryMap).put(newKey,newValue);
My idea is:
map1.get(subCategoryMap);
Return to another map I can divide this line into two lines and have:
map2 = map1.get(subCategoryMap); map2.put(newKey,newValue);
But I prefer one step That's why I tried
map1.get(subCategoryMap).put(newKey,newValue);
This doesn't work (I don't like. Put() on objects) Can I access the sub map and add it to the same line of code above me, or do I need to split it into 2 lines?
Solution
Using generics, you can:
Map<String,Map<String,String>> map1 = ... map1.get(category).put(subcategory,value);
If the map is not universal:
Map map1 = ... ((Map)map1.get(category)).put(subcategory,value);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码