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

[Kotlin][Collection] filter / filterNot / filterIndexed

by jinwo_o 2024. 8. 16.

주어진 조건과 일치하는 요소만 포함하는 목록을 반환합니다.

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]

 

filter - Kotlin Programming Language

 

kotlinlang.org

 

filterNot - Kotlin Programming Language

 

kotlinlang.org

 

filterIndexed - Kotlin Programming Language

 

kotlinlang.org