본문 바로가기

it-day/springboot

Map<String, List<dto 혹은 vo>>

Map<String, List<testDto>> testMap = (반복할 list).stream()
        .collect(Collectors.groupingBy(testDto02::gettest_cd));

 

여기에서!!  .collect(Collectors.groupingBy(testDto02::gettest_cd)); 부분

 

testDto02의 gettest_cd가 같은 것끼리 모으겠다 인듯

 

그러면 testMap의 결과는

 

{
    Math=[
        {studentId=S001, name=John Doe, grade=85},
        {studentId=S002, name=Jane Smith, grade=90}
    ],
    Science=[
        {studentId=S001, name=John Doe, grade=88},
        {studentId=S003, name=Alice Brown, grade=92}
    ]
}

 

{
    위의 gettest_cd 가 들어감=[ 리스트가 들어감 ],
    위의 gettest_cd 가 들어감=[ 리스트가 들어감 ],

 

이런 식으로 나올 것이다!!!

 

그것을 이용해 for문 돌리기!!

 

for (Map.Entry<String, List< testDto02 >> entry : testMap.entrySet()) {
    // Map.Entry<String, List< testDto02 >> entry의 key값
    String subject =  entry.getKey();
    // subject = 위의 데이터에서 Math와 Science이 해당된다
}

 

/*
Map<String, String> hashMap = new HashMap<>();
        
for (String key : hashMap.keySet()) {
    System.out.println("key : " + key);
    System.out.println("value : " + hashMap.get(key));
}
*/


//Map.Entry를 이용하면 위와같은 수고를 덜 수 있다.
Map<String, String> hashMap = new HashMap<>();
 
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
    System.out.println("key : " + entry.getKey());
    System.out.println("value : " + entry.getValue());
}