주어진 조건과 일치하는 요소만 포함하는 목록을 반환합니다.
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val evenNumbers = numbers.filter { it % 2 == 0 }}
println(evenNumbers) // [2, 4, 6]
주어진 조건자와 일치하지 않는 모든 요소를 포함하는 목록을 반환합니다.
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val notMultiplesOf3 = numbers.filterNot { number -> number % 3 == 0 }
println(notMultiplesOf3) // [1, 2, 4, 5, 7]
print("nice to meet you".filterNot { "aeiou".contains(it) }) // "nc t mt y"
주어진 조건과 일치하는 요소만 포함하는 목록을 반환합니다.
public inline fun <T> Iterable<T>.filterIndexed(predicate: (index: Int, T) -> Boolean): List<T> {
return filterIndexedTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterIndexedTo(destination: C, predicate: (index: Int, T) -> Boolean): C {
forEachIndexed { index, element ->
if (predicate(index, element)) destination.add(element)
}
return destination
}
val numbers: List<Int> = listOf(0, 1, 2, 3, 4, 8, 6)
val numbersOnSameIndexAsValue = numbers.filterIndexed { index, i -> index == i }
println(numbersOnSameIndexAsValue) // [0, 1, 2, 3, 4, 6]
'코틀린 > [Filtering] 필터 작업' 카테고리의 다른 글
[Kotlin][Collection] takeWhile / takeLastWhile (0) | 2024.08.28 |
---|---|
[Kotlin][Collection] partition (0) | 2024.08.21 |
[Kotlin][Collection] all / any / none (0) | 2024.08.08 |