-
[Kotlin] 스트림 함수(1)Kotlin 2019. 10. 17. 21:16반응형
1.map()
컬렉션 내 인자를 다른 값이나 타입으로 변환할 때 사용합니다.
fun main() { val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 음식 이름을 받아서, 이름의 문자열 길이로 변환합니다. foods.map { food -> food.length }.forEach { print("lenth = $it, ") } println() // 음식 이름을 소문자로 변환합니다. foods.map { food -> food.toLowerCase() }.forEach { print("$it, ") } }lenth = 4, lenth = 5, lenth = 5, lenth = 6, lenth = 15, lenth = 5, lenth = 4, rice, bread, berry, potato, button mushroom, melon, kiwi,2.mapIndexed()
컬렉션 내의 인자의 인덱스 값을 사용할 수 있게 해 줍니다.
val numbers = (10..20) numbers.mapIndexed{idx, number -> idx * number}.forEach { print("$it ") }0 11 24 39 56 75 96 119 144 171 2003.mapNotNull()
map()과 동일하게 인자들을 변환시키면서 변환 결과가 Null일 경우 제외시킵니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 음식 이름의 길이가 5 이하이면 음식 이름을 반환 하고 초과이면 null 값을 반환하여 제외 시킵니다. foods.mapNotNull { food -> if(food.length <= 5) food else null }.forEach { print("$it ") }Rice Bread Berry Melon Kiwi4.flatMap()
map()과 동일한 역할을 하지만 변환된 함수의 반환형이 Interable입니다.
하나의 인자에서 여러 인자로 mapping이 필요한 경우 사용합니다.
val numbers = 0..5 // 0부터 각 인자 끝까지 반환 합니다. numbers.flatMap { number -> 0..number }.forEach { print("$it ") }0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 55.groupBy()
컬렉션 내 인자들을 조건에 따라 분류하며, 각 인자들의 리스트를 포함하는 맵 형태로 결과를 반환합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 음식 이름 길이가 5이하인 경우 Short으로 분류하고 초과인 경우 Long으로 분류합니다. foods.groupBy { food -> if(food.length <= 5) "Short" else "Long" } .forEach { key, food -> println("key = $key, food = $food") }key = Short, food = [Rice, Bread, Berry, Melon, Kiwi] key = Long, food = [Potato, Button Mushroom]반응형'Kotlin' 카테고리의 다른 글
[Kotlin] 람다 (0) 2021.03.29 [Kotlin] 스트림 함수(2) (0) 2019.10.17 [Kotlin] for문 (0) 2019.09.27 [Kotlin] 자료형 (0) 2019.09.27 [Kotlin] 정의 (0) 2019.09.27