본문 바로가기
Back/Java

[JAVA] Stream Collectors.groupingBy 널(null) 사용하기

by 은z 2023. 4. 7.

상황

데이터를 grouping 해서 Map으로 리턴해야 하는 상황이다.

grouping할 key 값이 nullable한 상황인데, 

Map의 key값은 null이 될 수 없기때문에 문제가 발생했다.

아래와 같은 exception을 뱉었다.

Caused by: java.lang.NullPointerException: element cannot be mapped to a null key

 

🫥참고로, 만약 그룹핑할 key가 절대로 null이 아니라면 아래와 같이 간단하게 처리할 수 있다.

Map<String, List<ResponseDto>> map = list.stream().map(li ->
                    new ResponseDto(li)
            ).collect(Collectors.groupingBy(ResponseDto::getCode));

해결

 

✔️Null값이 있는 GroupBy Key!

Map<String, List<ResponseDto>> responseList = list.stream().map(ResponseDto::new)
                .collect(Collectors.toMap( // flag가 nullable -> Collectors.groupingBy 쓰면 에러 뱉음.
                        response -> response.getFlag() == null ? "F" : response.getFlag(), // key가 null이면 "F"를 넣어줌
                        fList -> { //list 수만큼 반복
                            List<ResponseDto> list = new ArrayList<>();
                            list.add(fList);
                            return list;
                        },
                        (oldList, newList) -> { // key 중복 처리
                            oldList.addAll(newList);
                            return oldList;
                        },
                        HashMap::new));

댓글