GOOGLE ADS

viernes, 22 de abril de 2022

Cómo recuperar datos del diccionario anidado en java

Tengo dos diccionarios agregados al diccionario principal. Cómo recuperar datos de un valor (que es un diccionario)

import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int count =2;

Dictionary parent_dic = new Hashtable();
Dictionary child1 = new Hashtable();
Dictionary child2 = new Hashtable();
Dictionary child = new Hashtable();

child1.put("1", "one");
child1.put("2", "two");
System.out.println("Child1" + child1);

child2.put("3", "three");
child2.put("4", "four");
System.out.println("Child2" + child2);

for(int each_c = 1; each_c <= count; each_c++) {
if(each_c==1) {
child = child1;
} else {
child = child2;
}
parent_dic.put(each_c,child);
}


System.out.println("Parent" + parent_dic);
System.out.println("test::: " + parent_dic.get(1));

}

}

¿Cómo obtener valor del valor resultante (que es el diccionario)?

Producción:

Child1{2=two, 1=one}
Child2{4=four, 3=three}
Parent{2={4=four, 3=three}, 1={2=two, 1=one}}
test::: {2=two, 1=one}

Cómo obtener el valor "dos" del diccionario de prueba anterior.


Solución del problema

Traté de reescribir su código de una manera que tuviera más sentido para mí.

También he agregado el uso de tipos adecuados, usar tipos sin formato en Java es peligroso. La última línea de mi código hace lo que creo que quieres. Tenga en cuenta la diferencia entre usar Integers como claves y Strings como claves.


public static void main(String[] args) {
Dictionary<Integer, Dictionary> parent_dic = new Hashtable();
Dictionary<String, String> child1 = new Hashtable();
Dictionary<String, String> child2 = new Hashtable();
child1.put("1", "one");
child1.put("2", "two");
System.out.println("Child1" + child1);
child2.put("3", "three");
child2.put("4", "four");
System.out.println("Child2" + child2);
parent_dic.put(1, child1);
parent_dic.put(2, child2);
System.out.println("Parent" + parent_dic);
System.out.println("test: " + parent_dic.get(1));
System.out.println("two: " + parent_dic.get(1).get("2"));
}

No hay comentarios.:

Publicar un comentario

Flutter: error de rango al acceder a la respuesta JSON

Estoy accediendo a una respuesta JSON con la siguiente estructura. { "fullName": "FirstName LastName", "listings...