필터링은 특정 조건을 만족하는 요소를 걸러내는 방식으로 이루어진다.
여기서 조건자는 람다 함수로, 컬렉션의 각 요소를 받아 불리언 값을 반환한다.
true는 해당 요소가 만족함을, false는 그렇지 않음을 의미한다.
원본 컬렉션을 변경하지 않고, 새로운 컬렉션을 반환환다.
filter : 해당 조건을 만족하는 요소들로 구성된 새로운 컬렉션을 반환한다. List와 Set에서는 결과가 List로, Map에서는 결과가 Map으로 반환된다.filterIndexed(): 인덱스를 사용해 조건을 적용할 수 있다.filterNot(): 조건이 false인 요소들만 필터링한다.val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3) // [three, four]
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10 }
println(filteredMap) // {key11=11}
val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
val filteredNot = numbers.filterNot { it.length <= 3 }
println(filteredIdx) // [two, four]
println(filteredNot) // [three, four]
filterIsInstance<T>(): 주어진 타입의 요소들만 필터링filterNotNull(): null이 아닌 요소들만 필터링val mixedList = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
mixedList.filterIsInstance<String>().forEach {
println(it.uppercase()) // TWO, FOUR
}
val numbers = listOf(null, "one", "two", null)
numbers.filterNotNull().forEach {
println(it.length) // 3, 3
}
partition(): 조건에 따라 컬렉션을 두 개의 리스트로 분할한다. 첫 번째 리스트에는 조건을 만족하는 요소들이, 두 번째 리스트에는 그렇지 않은 요소들이 포함된다.val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }
println(match) // [three, four]
println(rest) // [one, two]
any(): 하나라도 조건을 만족하면 true를 반환한다.none(): 조건을 만족하는 요소가 하나도 없다면 true를 반환한다.all(): 모든 요소가 조건을 만족하면 true를 반환한다.val numbers = listOf("one", "two", "three", "four")
println(numbers.any { it.endsWith("e") }) // true
println(numbers.none { it.endsWith("a") }) // true
println(numbers.all { it.endsWith("e") }) // false
println(emptyList<Int>().all { it > 5 }) // true
any()와 none()은 조건자 없이 호출할 수 있으며, 이 경우 컬렉션이 비어있는지 여부를 확인한다.
val numbers = listOf("one", "two", "three", "four")
val empty = emptyList<String>()
println(numbers.any()) // true
println(empty.any()) // false
println(numbers.none()) // false
println(empty.none()) // true