중첩 반복문을 처리하는 것과 같이,
리스트 안에 리스트로 존재하는 엔티티를 전부 하나의 리스트에 담기 위해 사용.
2차원을 1차원으로 평면화한다고 생각하면 된다.
보통 엔티티 리스트로 가져온 객체를 처리할 때 .stream.map(DTO::from).collect(Collectors.toList())
형태를 사용했었다.
레포지토리
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()
를 통해 담으면 됨!