woowacourse-study / 2022-modern-java-in-action

우아한테크코스 4기 모던 자바 인 액션 스터디
10 stars 4 forks source link

flatMap 이란? #45

Open sure-why-not opened 2 years ago

sure-why-not commented 2 years ago

문제

flatMap 은 어떤 상황에서 사용하는 것일까? 어떻게 동작하는 것일까?

선정 배경

map 을 주로 사용했기 때문에 flatMap 이 생소한데, 책의 예제만으로는 명확하게 이해되지 않아서 추가적인 정리와 실습을 해보면 좋을 것 같다.

관련 챕터

sure-why-not commented 2 years ago

스트림 평면화

.flatMap()은 Array나 Object로 감싸져 있는 모든 원소를 단일 원소 스트림으로 반환해준다.

image

  1. Hello가 split("")에 의해 ["H", "e", "l", "l", "o"] 로 분리되고, World가 split("")에 의해 ["W", "o", "r", "l", "d"]로 분리된다.
  2. Arrays.stream(T[] array)를 사용해 ["H", "e", "l", "l", "o"] 와 ["W", "o", "r", "l", "d"]를 각각 Stream으로 만든다.
  3. flatMap()을 사용해 여러 개의 Stream을 1개의 Stream으로 평평하게 합치고, Stream의 소스는 ["H", "e", "l", "l", "o", W", "o", "r", "l", "d"] 가 된다.
  4. distinct()에 의해 중복된 소스(l, o)가 제거된다.
  5. 중복이 제거된 ["H", "e", "l", "o", "W", "r", "d"]가 collect(toList())에 의해 수집된다.


String 이 아닌 2차원 배열을 예시로 들어보자.

        int[][] sample = new int[][]{
                {1, 2},
                {3, 4},
                {5, 6},
                {7, 8},
                {9, 10}
        };
        IntStream intStream = Arrays.stream(sample)
                .flatMapToInt(array -> Arrays.stream(array));

        intStream.forEach(System.out::println);

결과

1
2
3
4
5
6
7
8
9
10