모든 요소가 주어진 조건을 만족하면 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
'코틀린 > [Filtering] 필터 작업' 카테고리의 다른 글
[Kotlin][Collection] takeWhile / takeLastWhile (0) | 2024.08.28 |
---|---|
[Kotlin][Collection] partition (0) | 2024.08.21 |
[Kotlin][Collection] filter / filterNot / filterIndexed (0) | 2024.08.16 |