Stream API (map, flatMap)

김민규·2026년 9월 13일

겅부

목록 보기
3/18

🇶 Stream API의 map과 flatMap의 차이점을 설명하고, 각각의 활용 사례를 예시 코드와 함께 설명해주세요.

1. map

Stream의 요소를 1대1로 변환하는 연산이다.
아래 코드는 1~10으로 구성된 list 제곱을 구해 list2에 반환하는 코드이다.

 public static void main(String[] args) {
       List<Integer> list = IntStream.rangeClosed(1, 10)
               .boxed()
               .toList();

       List<Integer> list2 =
               list.stream().map(n ->(int) Math.pow(n,2)).collect(Collectors.toList());

   }

2. flatMap

JCF의 차원을 한단계 낮추어, 자료구조를 단순화한다.
아래 코드에서는 map(학과, map<이름,번호>) 구조에서 map<학과,List<이름,번호 번갈아>>
구조로 바꾸었다.

 public class Main {
   public static void main(String[] args) {
       Map<String, Map<String, String>> departments = Map.of(
               "컴퓨터공학과", Map.of(
                       "김민규", "010-1111-1111",
                       "김명운", "010-2222-2222",
                       "박도현", "010-3333-3333"
               ),
               "전자공학과", Map.of(
                       "신정우", "010-4444-4444",
                       "이태호", "010-5555-5555"
               )
       );

       Map<String, List<String>> result =
               departments.entrySet().stream()
                       .collect(Collectors.toMap(
                               Map.Entry::getKey,
                               entry -> entry.getValue().entrySet().stream()
                                       .flatMap(e -> Stream.of(e.getKey(), e.getValue()))
                                       .toList()
                       ));

   }


}

0개의 댓글