Baran Topal

Baran Topal


May 2024
M T W T F S S
« Feb    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories


Map of maps of maps of..a map inception in Java

baranbaran

Long ago, I needed to have a map having a map as a value of the parent map 😛

Map<String, Map<String, String> myMap = new HashMap<String Map<String, String>>();

void addEntryToMap(String key, subKey, value) {
 Map<String, String> subMap = myMap.get(key);
 if (subMap == null) {
 subMap = new HashMap<String, String>();
 myMap.put(key, subMap);
 }
 subMap.put(subKey, value);
}

and I added the utility methods to do certain operations,

String getEntry(String key, String subKey) {
 String value = null;
 Map<String, String> subMap = myMap.get(key);
 if (subMap != null) {
 value = subMap.get(subKey);
 }
 return value;
}

List<String> getAllEntriesForKey(String key) {
 Map<String, String> subMap = myMap.get(key);
 if (subMap != null) {
 return new ArrayList<String>(subMap.values());
 }
 return new ArrayList<String>(); // or you could return null here, just depends what you prefer
}