2014-10-04 7 views
7

Come procedo con l'iterazione di una HashMap nidificata?Iterate attraverso l'hashmap nidificato

Il HashMap è configurazione come questa:

HashMap<String, HashMap<String, Student>> 

Dove Student è un oggetto contenente una variabile name. Se per esempio la mia HashMap si presentava così (seguenti non è il mio codice, è solo per simulare quello che potrebbe essere il contenuto del hashmap)

hm => HashMap<'S', Hashmap<'Sam', SamStudent>> 
     HashMap<'S', Hashmap<'Seb', SebStudent>> 
     HashMap<'T', Hashmap<'Thomas', ThomasStudent>> 

Come potrei scorrere tutti i tasti delle lettere singole, allora ogni tasto nome completo, quindi estrarre il nome dello studente?

risposta

11
for (Map.Entry<String, HashMap<String, Student>> letterEntry : students.entrySet()) { 
    String letter = letterEntry.getKey(); 
    // ... 
    for (Map.Entry<String, Student> nameEntry : letterEntry.getValue().entrySet()) { 
     String name = nameEntry.getKey(); 
     Student student = nameEntry.getValue(); 
     // ... 
    } 
} 
+0

perfetta e miglior codice per attraversare HashMaps di HashMaps. Grazie Brett – vkrams

8

Java 8 lambda e Map.forEach rendono bkail's answer più concisa:

outerMap.forEach((letter, nestedMap) -> { 
    //... 
    nestedMap.forEach((name, student) -> { 
     //... 
    }); 
    //... 
});