[Java] List<List<Entity>> 처리하기: Stream.flatMap()

민지·2023년 11월 1일
0

Java

목록 보기
2/9
post-thumbnail

Stream.flatMap()

사용 목적

중첩 반복문을 처리하는 것과 같이,
리스트 안에 리스트로 존재하는 엔티티를 전부 하나의 리스트에 담기 위해 사용.

2차원을 1차원으로 평면화한다고 생각하면 된다.

기존 1차원 방법

보통 엔티티 리스트로 가져온 객체를 처리할 때 .stream.map(DTO::from).collect(Collectors.toList()) 형태를 사용했었다.

2차원 객체 List 하나에 담기

레포지토리

public interface HistoryRepository extends JpaRepository<History, Long> {

    @Query("select distinct h from History h " +
            "left join fetch h.company c " +
            "left join fetch h.resume r " +
            "left join fetch h.interview i " +
            "left join fetch i.prediction p " +
            "left join fetch c.companyInfo ci " +
            "where c.user.userId = :userId")
    List<History> findHistoryWithResumeAndInterviewAndCompanyInfoByUser(@Param("userId") Long userId);
}

서비스

public ResponseMain viewMain(User user) {

   List<History> mainInfos = historyRepository.findHistoryWithResumeAndInterviewAndCompanyInfoByUser(user.getUserId());
   
   List<ResponseMainInterview> mainInterviews = mainInfos.stream()
                .flatMap(info -> info.getInterview().getPrediction().stream()
                        .map(prediction -> ResponseMainInterview.from(info, prediction)))
                .collect(Collectors.toList());

    return ResponseMain.from(mainInterviews);
}

이렇게 flatMap() 을 사용해서 푼 다음,
안에는 리스트로 존재하는 객체를 빼서,
stream() 으로 분리한 후 하나씩 map() 을 통해 순환하며 리스트에 담는다.
그리고 이걸 collect() 를 통해 담으면 됨!

profile
개발의, 개발에 의한, 개발을 위한 기록장

0개의 댓글

관련 채용 정보