자바 8에서는 컬렉션에 포함된 자료들을
손쉽게 다룰 수 있도록 스트림(stream) 기능을 제공.
Kotlin은 스트림 대신 이와 유사한 역할을 하는 함수들을
표준 라이브러리에서 제공하며, 확장 함수 형태로 제공된다.
변환
map()
컬랙션 내 인자를 변환하여 반환할 때 사용
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London")
// SEOUL, TOKYO, LONDON
cities.map { city -> city.toUpperCase() }.forEach { println(it) }
// 5, 5, 6
cities.map{city -> city.length}.forEach { println(it) }
}
mapIndexed()
컬랙션에 포함된 인자의 index 값을 변환하여 사용 가능
fun main(args: Array<String>) {
val numbers = 0..5
// 0, 1, 4, 9, 16, 25
numbers.mapIndexed { idx, number -> idx * number }.forEach { println(it) }
}
mapNotNull()
컬렉션 내 인자를 변환함과 동시에, 변환한 결과가 Null인 경우 이를 무시.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London")
// Seoul, Tokyo
cities.mapNotNull { city -> if(city.length <=5) city else null }.forEach { println(it) }
}
flatMap()
map() 함수와 비슷하지만 다른 부분이 변환 함수의 반환형이 Interable이다.
즉, 하나의 인자에서 여러 개의 인자로 매핑이 필요할 때 사용
class FlatMap {
val numbers = 0..10
fun flatMap() {
numbers.flatMap { number -> 1..number }.forEach { println("$it") }
}
}
groupBy()
컬렉션 인자들을 기준에 따라 분류하고 각 List를 포함한 맵 형태로 결과를 반환.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London")
// A [Seoul, Tokyo], B [London]
cities.groupBy { city -> if (city.length <= 5) "A" else "B" }
.forEach { (key, cities) -> println("$key $cities") }
}
필터
filter() : 필터
List 내에 인자들 중 조건에 일치하는 인자만 필터링.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "View")
// Seoul, Tokyo
cities.filter{ city -> city.length <= 5}.forEach{ println(it) }
}
take()
- take() : 컬렉션 내 인자들 중 앞에서부터 take()의 인자로 받은 개수만큼만을 인자로 갖는 List를 반환.
- takeLast() : take() 함수와 반대로 뒤에서부터 적용해 순차적으로 반환한다.
- takeWhile() : 첫 번째 인자부터 시작하여 주어진 조건을 만족하는 인자까지를 포함하는 List를 반환.
- takeLastWhile() : takeLastWhile() 함수와 반대로 뒤에서부터 적용해 반환.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// Seoul, Tokyo
cities.take(2) .forEach { println(it) }
// London, NYC, Singapore
cities.takeLast(3) .forEach { println(it) }
// Seoul, Tokyo
cities.takeWhile { city -> city.length <= 5 } .forEach { println(it) }
// Singapore
cities.takeLastWhile { city -> city.length > 5 } .forEach { println(it) }
}
drop()
take() 함수와 반대로 조건을 만족하는 항목을 제외한 List를 반환.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// London, NYC, Singapore
cities.drop(2).forEach { println(it) }
// Seoul, Tokyo
cities.dropLast(3).forEach { println(it) }
// NYC, Singapore
cities.dropWhile { city -> city.length <= 5 }.forEach { println(it) }
// Seoul, Tokyo, London, NYC
cities.dropLastWhile { city -> city.length > 5 }.forEach { println(it) }
}
first(), last()
컬렉션 내 첫 번째 인자를 반환.
단순히 리스트 내에서 첫 번째에 위치하는 인자를 반환하는 것뿐 아니라, 특정 조건을 만족하는 첫 번째 인자를 반환하도록 구성하는 것도 가능.
조건을 만족하는 인자가 없는 경우엔 NoSuchElementException 예외를 발생시키며, firstOnNull() 함수를 사용하면 널 값을 반환하도록 할 수 있다.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// Seoul
println(cities.first())
// Singapore
println(cities.last())
// London
println(cities.first { it.length > 5 })
// null
println(cities.firstOrNull { it.length > 10 })
}
distinct()
컬렉션 내에 중복된 항목을 걸러낸 결과를 반환.
항목의 중복 여부는 equals()로 판단하며,distinctBy()를 사용하여 중복 여부를 판단을 설정 가능.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "Seoul", "Tokyo")
// Seoul, Tokyo, London
cities.distinct().forEach { println(it) }
// Seoul, London // 도시 이름의 길이를 판단 기준으로 사용
cities.distinctBy { it.length }.forEach { println(it) }
}
조합 및 합계
zip()
두 컬랙션의 자료들을 조합하여 새로운 자료를 만들 때 사용.
두 컬렉션 간 자료의 개수가 달라도 되고 더 적은 개수에 컬랙션 쪽으로 따라간다.
조합된 결과는 Pair로 만들어주며, 원할 경우 규칙도 정의가 가능.
fun main(args: Array<String>) {
val cityCodes = listOf("SEO", "TOK", "MTV", "NYC")
val cityNames = listOf("Seoul", "Tokyo", "Mountain View")
// Pair 형태로 출력
cityCodes.zip(cityNames).forEach { println(it) }
// 사용자가 직접 정의
cityCodes.zip(cityNames) { code, name -> "$code $name" }.forEach { println(it) }
}
joinToString()
컬렉션 내 자료를 문자열 형태로 변환함과 동시에, 이를 조합하여 하나의 문자열로 생성.
몇 가지 인자를 함께 전달하면 자신이 원하는 형태로 출력 문자열을 구성하는 것도 가능.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
//Seoul, Tokyo, London, NYC, Singapore
println(cities.joinToString())
// Seoul & Tokyo & London & NYC & Singapore
println(cities.joinToString(separator = " & "))
}
count()
컬렉션 내 포함된 자료의 개수를 반환.
별도의 조건식을 추가하면 해당 조건을 만족하는 자료의 개수를 반환 가능.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// 5
println(cities.count())
// 3
println(cities.count { it.length <= 5 })
}
reduce()
컬렉션 내 자료들을 모두 합쳐 하나의 값으로 만들어주는 역할.
fun main(args: Array<String>) {
val cities = listOf(1, 2, 3, 4, 5)
// 15
println(cities.reduce { acc, s -> acc + s })
}
fold()
reduce() 함수와 거의 동일한 역할을 하지만, 초깃값을 지정 가능.
fun main(args: Array<String>) {
val cities = listOf(1, 2, 3, 4, 5)
// 35
println(cities.fold(20) { acc, s -> acc + s })
}
기타
any()
컬렉션 내 단 하나의 자료라도 존재하면 true, 그렇지 않으면 false를 반환.
인자로 조건식을 전달할 경우, 해당 조건식을 만족하는 자료의 유무 여부를 반환.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// true
println(cities.any { it.length >= 5 })
}
none()
any() 함수와 반대 작업을 수행, 컬렉션이 비어있는지 여부를 반환.
any() 함수와 마찬가지로, 조건식을 전달하여 해당 조건식에 만족하는 자료의 유무를 판단.
fun main(args: Array<String>) {
val cities = listOf("Seoul", "Tokyo", "London", "NYC", "Singapore")
// true
println(cities.none { it.length >= 10 })
}
max(), min(), average()
최댓값, 최솟값, List의 평균값 반환
class maxMinAverage {
val numbers = listOf(1, 2, 3)
fun any() {
println(numbers.max())
println(numbers.min())
println(numbers.average())
}
}
Kotlin Stream Function
https://leveloper.tistory.com/134
'Kotlin > Basic' 카테고리의 다른 글
object, companion object (0) | 2024.01.02 |
---|---|
Kotlin DSL, buildSrc 의존성 주입 (0) | 2023.12.07 |
Closure, Scope Function (let, also, run, apply, with) (0) | 2022.03.11 |
Coroutine (0) | 2022.01.17 |