filter

inline fun <T> Array<out T>.filter(predicate: (T) -> Boolean): List<T>
inline fun ByteArray.filter(predicate: (Byte) -> Boolean): List<Byte>
inline fun ShortArray.filter(predicate: (Short) -> Boolean): List<Short>
inline fun IntArray.filter(predicate: (Int) -> Boolean): List<Int>
inline fun LongArray.filter(predicate: (Long) -> Boolean): List<Long>
inline fun FloatArray.filter(predicate: (Float) -> Boolean): List<Float>
inline fun DoubleArray.filter(predicate: (Double) -> Boolean): List<Double>
inline fun BooleanArray.filter(predicate: (Boolean) -> Boolean): List<Boolean>
inline fun CharArray.filter(predicate: (Char) -> Boolean): List<Char>
inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>

Returns a list containing only elements matching the given predicate.

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val evenNumbers = numbers.filter { it % 2 == 0 }
val notMultiplesOf3 = numbers.filterNot { number -> number % 3 == 0 }

assertPrints(evenNumbers, "[2, 4, 6]")
assertPrints(notMultiplesOf3, "[1, 2, 4, 5, 7]") 
   //sampleEnd
}

inline fun UIntArray.filter(predicate: (UInt) -> Boolean): List<UInt>
inline fun ULongArray.filter(predicate: (ULong) -> Boolean): List<ULong>
inline fun UByteArray.filter(predicate: (UByte) -> Boolean): List<UByte>
inline fun UShortArray.filter(predicate: (UShort) -> Boolean): List<UShort>

Returns a list containing only elements matching the given predicate.

Since Kotlin

1.3

Samples

import samples.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   val numbers: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)
val evenNumbers = numbers.filter { it % 2 == 0 }
val notMultiplesOf3 = numbers.filterNot { number -> number % 3 == 0 }

assertPrints(evenNumbers, "[2, 4, 6]")
assertPrints(notMultiplesOf3, "[1, 2, 4, 5, 7]") 
   //sampleEnd
}

inline fun <K, V> Map<out K, V>.filter(predicate: (Map.Entry<K, V>) -> Boolean): Map<K, V>

Returns a new map containing all key-value pairs matching the given predicate.

The returned map preserves the entry iteration order of the original map.

Samples

import samples.*
import kotlin.test.*
import java.util.*
fun main() { 
   //sampleStart 
   val originalMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3)

val filteredMap = originalMap.filter { it.value < 2 }

assertPrints(filteredMap, "{key1=1}")
// original map has not changed
assertPrints(originalMap, "{key1=1, key2=2, key3=3}")

val nonMatchingPredicate: ((Map.Entry<String, Int>)) -> Boolean = { it.value == 0 }
val emptyMap = originalMap.filter(nonMatchingPredicate)
assertPrints(emptyMap, "{}") 
   //sampleEnd
}