2014-10-04 2 views
7

중첩 된 HashMap을 통해 반복하는 방법은 무엇입니까?중첩 된 해시 맵을 반복합니다.

HashMap 이런 설정이다 Student 변수 name 함유 목적

HashMap<String, HashMap<String, Student>> 

. 예를 들어 제의 HashMap은

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

가 어떻게 각각의 단일 문자 키의 모든 반복 수 (다음은이 해시 맵의 내용이 될 수있는 것을 시뮬레이션 그냥, 내 코드가 아닙니다)이 닮은 경우 성함을 입력 한 다음 학생 이름을 빼십시오.

답변

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

완벽한 최상의 코드를 HashMaps을의 HashMaps을을 통과하십시오. Brett에게 감사드립니다. – vkrams

8

자바 8 람다와 Map.forEachbkail's answer 더 간결합니다

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