본문 바로가기
코틀린/[Filtering] 필터 작업

[Kotlin][Collection] all / any / none

by jinwo_o 2024. 8. 8.

모든 요소가 주어진 조건을 만족하면 true 를 반환합니다.

배열에 요소가 하나도 없을 경우, 해당 요소가 조건을 만족하지 않는 것이 없으므로 true 를 반환합니다.

public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return true
    for (element in this) if (!predicate(element)) return false
    return true
}


val isEven: (Int) -> Boolean = { it % 2 == 0 }
val zeroToTen = 0..10
println(zeroToTen.all { isEven(it) }) // false
println(zeroToTen.all(isEven)) // false

val evens = zeroToTen.map { it * 2 }
println(evens.all { isEven(it) }) // true

val emptyList = emptyList<Int>()
println(emptyList.all { false }) // true

 

컬렉션에 요소가 하나 이상 있으면 true 를 반환합니다.

public fun <T> Iterable<T>.any(): Boolean {
    if (this is Collection) return !isEmpty()
    return iterator().hasNext()
}


val emptyList = emptyList<Int>()
println("emptyList.any() is ${emptyList.any()}") // false

val nonEmptyList = listOf(1, 2, 3)
println("nonEmptyList.any() is ${nonEmptyList.any()}") // true

 

주어진 조건과 일치하는 요소가 없으면 true 를 반환합니다.

public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return true
    for (element in this) if (predicate(element)) return false
    return true
}


val list = listOf(1, 2, 3, 4)
print(list.none { it < 0 }) // true

 

all - Kotlin Programming Language

 

kotlinlang.org

 

any - Kotlin Programming Language

 

kotlinlang.org

 

none - Kotlin Programming Language

 

kotlinlang.org