목표
Java Stream API의 map()와 flatMap() 메서드의 차이 이해하기
Stream
- Stream이란
- 데이터의 연속적인 흐름을 다루는 API로 Java 8부터 도입된 API이다.
- 주로, 컬렉션이나 배열과 같은 데이터 소스를 처리하는 데 사용한다.
- Stream으로 처리하는 경우 정렬, 필터링 연산도 함께 처리할 수 있다.
Map & FlatMap
both have intermediate stream operation and return another stream as method output.
Both of the functions map() and flatMap are used for transformation and mapping operations.
map() function produces one output for one input value, whereas flatMap() function produces an arbitrary number of values as output (ie zero or more than zero) for each input value.
두 메서드 다 Stream 중간 연산자이며, 처리된 Stream을 반환한다. 주로, 변형과 매핑 연산으로 사용된다.
map()은 하나의 Input을 처리하여 하나의 Output을 만든다. (1:1 관계) flatMap()은 각 Input을 처리하여 임의의 Output을 만든다. (1:N 관계)
Map
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
- Stream의 각 요소를 변환하여 새로운 요소로 매핑하는 중간 연산자이다. (1:1 매핑)
- map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results.
stream & map을 통한 처리
@Test
fun test() {
val names = listOf("john", "jane", "mike")
val upperNames = names.stream()
.map(String::uppercase)
.collect(Collectors.toList())
println(upperNames)
}
// [JOHN, JANE, MIKE]
for 문을 통한 처리
@Test
fun test() {
val upperNames2 = mutableListOf<String>()
for (name in names) {
upperNames2.add(name.uppercase())
}
println(upperNames2)
}
// [JOHN, JANE, MIKE]
Optional & Map
Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
- Map() 메서드는 Optional을 반환받아야 하는 상황에서도 사용할 수 있다.
- map()은 연산을 처리한 후, 내부적으로 추가적으로 래핑 하여 반환한다.
FlatMap
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Function<? super T, ? extends Stream<? extends R>> mapper
입력 값 T 타입을 -> Stream<R> 타입으로 변환한다.
flatmap()은 입력 값을 받아 스트림 타입으로 변환한다.
- flatMap()은 Stream의 각 요소를 Stream으로 변환한 후, 하나의 스트림으로 평면화합니다.
- 1:N 관계에 있는 각 요소를 처리해준다. (평면화)
- flatMap() can be used where we have to flatten or transform out the string
@Test
fun test() {
val arr = listOf(
listOf("a", "b"),
listOf("c", "d")
)
val lists = arr.stream()
.toList()
val flatArr = arr.stream()
.flatMap { it.stream() }
.toList()
println(lists)
println(flatArr)
}
// [[a, b], [c, d]]
// [a, b, c, d]
// 하나의 주문에 여러 개의 아이템이 존재
List<Order> orders = Arrays.asList(
new Order(Arrays.asList(
new Item("Apple", 1.0),
new Item("Banana", 2.0)
)),
new Order(Arrays.asList(
new Item("Orange", 3.0)
))
);
// 모든 주문에서 상품 이름만 추출
List<String> itemNames = orders.stream()
.flatMap(order -> order.getItems().stream())
.map(Item::getName)
.collect(Collectors.toList());
📌 결론
- map() : 각 요소에 특정 메서드를 적용한다.
- flatMap() : 각 요소를 하나의 스트림으로 변환한다.
참고 자료
https://www.geeksforgeeks.org/difference-between-map-and-flatmap-in-java-stream/
'JAVA' 카테고리의 다른 글
Java 객체 비교: equals()와 hashCode()로 보는 물리적 vs 논리적 동등성 (0) | 2025.03.31 |
---|---|
Java 버전별 변화 및 주요 기능 - java 8, 11, 17, 21 (0) | 2025.03.14 |
Java 21 가상 스레드란? 기존 OS 스레드와의 차이점 정리 (0) | 2025.02.18 |
Java 프로그램 실행 과정, JVM 구조 이해하기 (0) | 2025.02.15 |
Java string, stringbuilder를 이용해 문자열 합치기 (0) | 2024.11.23 |
목표
Java Stream API의 map()와 flatMap() 메서드의 차이 이해하기
Stream
- Stream이란
- 데이터의 연속적인 흐름을 다루는 API로 Java 8부터 도입된 API이다.
- 주로, 컬렉션이나 배열과 같은 데이터 소스를 처리하는 데 사용한다.
- Stream으로 처리하는 경우 정렬, 필터링 연산도 함께 처리할 수 있다.
Map & FlatMap
both have intermediate stream operation and return another stream as method output.
Both of the functions map() and flatMap are used for transformation and mapping operations.
map() function produces one output for one input value, whereas flatMap() function produces an arbitrary number of values as output (ie zero or more than zero) for each input value.
두 메서드 다 Stream 중간 연산자이며, 처리된 Stream을 반환한다. 주로, 변형과 매핑 연산으로 사용된다.
map()은 하나의 Input을 처리하여 하나의 Output을 만든다. (1:1 관계) flatMap()은 각 Input을 처리하여 임의의 Output을 만든다. (1:N 관계)
Map
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
- Stream의 각 요소를 변환하여 새로운 요소로 매핑하는 중간 연산자이다. (1:1 매핑)
- map() can be used where we have to map the elements of a particular collection to a certain function, and then we need to return the stream which contains the updated results.
stream & map을 통한 처리
@Test
fun test() {
val names = listOf("john", "jane", "mike")
val upperNames = names.stream()
.map(String::uppercase)
.collect(Collectors.toList())
println(upperNames)
}
// [JOHN, JANE, MIKE]
for 문을 통한 처리
@Test
fun test() {
val upperNames2 = mutableListOf<String>()
for (name in names) {
upperNames2.add(name.uppercase())
}
println(upperNames2)
}
// [JOHN, JANE, MIKE]
Optional & Map
Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
- Map() 메서드는 Optional을 반환받아야 하는 상황에서도 사용할 수 있다.
- map()은 연산을 처리한 후, 내부적으로 추가적으로 래핑 하여 반환한다.
FlatMap
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
Function<? super T, ? extends Stream<? extends R>> mapper
입력 값 T 타입을 -> Stream<R> 타입으로 변환한다.
flatmap()은 입력 값을 받아 스트림 타입으로 변환한다.
- flatMap()은 Stream의 각 요소를 Stream으로 변환한 후, 하나의 스트림으로 평면화합니다.
- 1:N 관계에 있는 각 요소를 처리해준다. (평면화)
- flatMap() can be used where we have to flatten or transform out the string
@Test
fun test() {
val arr = listOf(
listOf("a", "b"),
listOf("c", "d")
)
val lists = arr.stream()
.toList()
val flatArr = arr.stream()
.flatMap { it.stream() }
.toList()
println(lists)
println(flatArr)
}
// [[a, b], [c, d]]
// [a, b, c, d]
// 하나의 주문에 여러 개의 아이템이 존재
List<Order> orders = Arrays.asList(
new Order(Arrays.asList(
new Item("Apple", 1.0),
new Item("Banana", 2.0)
)),
new Order(Arrays.asList(
new Item("Orange", 3.0)
))
);
// 모든 주문에서 상품 이름만 추출
List<String> itemNames = orders.stream()
.flatMap(order -> order.getItems().stream())
.map(Item::getName)
.collect(Collectors.toList());
📌 결론
- map() : 각 요소에 특정 메서드를 적용한다.
- flatMap() : 각 요소를 하나의 스트림으로 변환한다.
참고 자료
https://www.geeksforgeeks.org/difference-between-map-and-flatmap-in-java-stream/
'JAVA' 카테고리의 다른 글
Java 객체 비교: equals()와 hashCode()로 보는 물리적 vs 논리적 동등성 (0) | 2025.03.31 |
---|---|
Java 버전별 변화 및 주요 기능 - java 8, 11, 17, 21 (0) | 2025.03.14 |
Java 21 가상 스레드란? 기존 OS 스레드와의 차이점 정리 (0) | 2025.02.18 |
Java 프로그램 실행 과정, JVM 구조 이해하기 (0) | 2025.02.15 |
Java string, stringbuilder를 이용해 문자열 합치기 (0) | 2024.11.23 |