¿Cómo puedo actualizar un mapa dentro de un mapa?

Tengo un Map of Maps que se ve así:

Map<String, Map<String, Object>> data;

I want to update the inner map.

Should I do the following everytime I want to update the innermap or is there any other direct/better way of accomplishing it?

Map<String, Object> innerMap = data.get("outer_key");
innerMap.put("inner_key", value);
data.put("outer_key", innerMap);

preguntado el 30 de enero de 12 a las 19:01

inner.put("inner_key", value);, should that have been innerMap.put("inner_key", value);? -

You don't need the third line. You're sharing a reference to a single instance (the inner map). -

2 Respuestas

I think you may have a typo in there and I'm assuming inner es en realidad innerMap. I would probably change it a bit to account for null values in the outer map:

Map<String, Object> innerMap = data.get("outer_key");

// Added this if statement to handle null values in the outer map.
if (innerMap == null) {
    innerMap = new HashMap<String, Object>();
    data.put("outer_key", innerMap);

innerMap.put("inner_key", value);
// data.put("outer_key", innerMap); <-- This is not needed, innerMap is already a value in
                                     // the outer map.

Respondido el 30 de enero de 12 a las 23:01

Thanks, The "<-- This is not needed ..." part helps!! - 500865

You may consider using the google guava library, which has a Table class (basically map of maps):


Then you have available a put method that takes row, column, and value (which is a bit simpler).

Respondido el 30 de enero de 12 a las 23:01

Thanks for the information. Good to know about the guava library. - 500865

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.