Java - add key / value to map within map in 1 line of code?

I have a HashMap 1 that contains 5 keys, all of which have Hashmaps values. I want to add key / value pairs to these sub-Maps.

map1.get(subCategoryMap).put(newKey, newValue); 

My thinking:

map1.get(subCategoryMap);

returns another card. I could split this line into two lines and have:

map2 = map1.get(subCategoryMap);
map2.put(newKey, newValue);

But I would prefer to do it in one step. That's why i try

map1.get(subCategoryMap).put(newKey, newValue); 

This does not work (do not like .put () for the object). Is it possible to access the sub-map and add to it in the same line of code as me, or do I need to split it into two lines?

+3
source share
8 answers

With generics, you can:

Map<String, Map<String, String>> map1 = ...
map1.get(category).put(subcategory, value);

If the cards are not shared:

Map map1 = ...
((Map)map1.get(category)).put(subcategory, value);
+14
source
((Map)map1.get(subCategoryMap)).put(newKey, newValue);

Or, use generics:

Map<X, Map<Y,Z>> map1;

...

map1.get(subCategoryMap).put(newKey, newValue);

NullPointerException, map1 subCategoryMap.

+9

( , , )...

, . ( ) , .

. -, , , , . , , .

, Generics , - ; , , .

, , , , , , , , , , , .

, - . - .

dataHolder.put(category, newKey, newVale);

( , ), .

( , ) , - , , "" - ( - - , ), .

+3

Generics, HashMap Object, , :

((HashMap)map1.get(subCategoryMap)).put(newKey, newValue);

, .

0

, , . .

0

map1 - Map<OuterKey, Map<InnerKey, MyValue>>, . , , subCategoryMap map1NullPointerException.

0

((HashMap)map1.get(subCategoryMap)).put(newKey, newValue);

, Java 5 Java 6, generic, HashMap

0

, :

Map<String,Map<String,Integer>> map = new HashMap<String,Map<String,Integer>>();
map.put("Test", new HashMap<String,Integer>());
map.get("Test").put("Some", 1);
0

Source: https://habr.com/ru/post/1716605/


All Articles