← Volver
Recorrer Map en Java
Publicado el 14 de febrero de 2026
Java
Creamos el Map.
Map<Libro, ArrayList<Integer>> mapaLibros = new HashMap<>();
mapaLibros.put(new Libro("maria", "pepa", 15.20), new ArrayList<>());
mapaLibros.put(new Libro("jose", "pepe", 12.20), new ArrayList<>());
mapaLibros.put(new Libro("cristian", "carlos", 15.20), new ArrayList<>());
Recorrer el Map creando un Set.
Set<Map.Entry<Libro, ArrayList<Integer>>> entradas = mapaLibros.entrySet();
for ( Map.Entry<Libro, ArrayList<Integer>> e:entradas){
ArrayList<Integer> notas = e.getValue();
for (int i = 0; i < 3; i++) {
notas.add(getNumeroAleatorio(1,10));
}
}
for ( Map.Entry<Libro, ArrayList<Integer>> e:entradas){
System.out.println(e.getKey());
ArrayList<Integer> notas = e.getValue();
System.out.println(notas);
}Serializar/Deserializar
//SERIALIZAR
Gson json = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();
String mapaString = json.toJson(mapaLibros);
System.out.println(mapaString);
//DESERIALIZAR
Type tipo = new TypeToken<Map<Libro, ArrayList<Integer>>>(){}.getType();
Map<Libro, ArrayList<Integer>> mapaRecuperado = json.fromJson(mapaString, tipo);
for ( Map.Entry<Libro, ArrayList<Integer>> e:mapaRecuperado.entrySet()){
System.out.println(e.getKey());
ArrayList<Integer> notas = e.getValue();
System.out.println(notas);
}