-
[Kotlin] 스트림 함수(2)Kotlin 2019. 10. 17. 21:32반응형
1.filter()
컬렉션 내 인자들 중 주어진 조건과 일치하는 인자들만 반환합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 음식 이름 길이가 5이하인 경우만 반환합니다. foods.filter { food -> food.length <= 5 }.forEach { print("$it ") }
Rice Bread Berry Melon Kiwi
2.take()
컬렉션 내 인자들 중 take()에서 인자로 받은 개수만큼의 인자를 리스트로 반환합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 첫 번째 인자만 가져옵니다. foods.take(1).forEach { println(it) }
Rice
3.takeLast()
컬렉션 내 인자들 중 takeLast()에서 인자로 받은 개수만큼 뒤에서부터 인자를 리스트로 반환합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 마지막 인자만 가져옵니다. foods.takeLast(1).forEach { println(it) }
Kiwi
4.takeWhile()
첫 번째 인자부터 주어진 조건에 만족하는 인자까지 포함하는 리스트를 반환합니다.
주어진 조건에 만족하지 않는 인자가 나오면 뒤에 모든 인자를 무시합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 이름의 길이가 5이하인 것만 반환 합니다. // Potato 뒤에 5이하인 인자가 있지만 무시합니다. foods.takeWhile { food -> food.length <= 5 }.forEach { print("$it ") }
Rice Bread Berry
5.takeLastWhile()
takeWhile()과 동일한 역할을 하지만 마지막 인자부터 시작합니다.
val foods = listOf("Rice", "Bread", "Berry", "Potato", "Button Mushroom", "Melon", "Kiwi") // 이름의 길이가 5이하인 것만 반환 합니다. // Button Mushroom 앞에 5이하인 인자가 있지만 무시합니다. foods.takeLastWhile { food -> food.length <= 5 }.forEach { print("$it ") }
Melon Kiwi
반응형'Kotlin' 카테고리의 다른 글
[Kotlin] 코틀린이란 (0) 2021.04.02 [Kotlin] 람다 (0) 2021.03.29 [Kotlin] 스트림 함수(1) (0) 2019.10.17 [Kotlin] for문 (0) 2019.09.27 [Kotlin] 자료형 (0) 2019.09.27