Filtering

    The standard library contains a group of extension functions that let you filter collections in a single call. These functions leave the original collection unchanged, so they are available for both mutable and read-only collections. To operate the filtering result, you should assign it to a variable or chain the functions after filtering.

    The basic filtering function is . When called with a predicate, filter() returns the collection elements that match it. For both List and Set, the resulting collection is a List, for Map it’s a Map as well.

    To filter collections by negative conditions, use filterNot(). It returns a list of elements for which the predicate yields false.

    1. fun main() {
    2. //sampleStart
    3. val numbers = listOf("one", "two", "three", "four")
    4. val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
    5. val filteredNot = numbers.filterNot { it.length <= 3 }
    6. println(filteredIdx)
    7. println(filteredNot)

    There are also functions that narrow the element type by filtering elements of a given type:

    • returns collection elements of a given type. Being called on a List<Any>, filterIsInstance<T>() returns a List<T>, thus allowing you to call functions of the T type on its items.
    • filterNotNull() returns all non-null elements. Being called on a List<T?>, filterNotNull() returns a List<T: Any>, thus allowing you to treat the elements as non-null objects.
    1. fun main() {
    2. //sampleStart
    3. val numbers = listOf(null, "one", "two", null)
    4. numbers.filterNotNull().forEach {
    5. println(it.length) // length is unavailable for nullable Strings
    6. }
    7. //sampleEnd
    8. }

    Finally, there are functions that simply test a predicate against collection elements:

    • returns true if at least one element matches the given predicate.
    • all() returns true if all elements match the given predicate. Note that all() returns true when called with any valid predicate on an empty collection. Such behavior is known in logic as .
    1. fun main() {
    2. //sampleStart
    3. val numbers = listOf("one", "two", "three", "four")
    4. println(numbers.any { it.endsWith("e") })
    5. println(numbers.none { it.endsWith("a") })
    6. println(numbers.all { it.endsWith("e") })
    7. println(emptyList<Int>().all { it > 5 }) // vacuous truth
    8. //sampleEnd
    9. }

    any() and none() can also be used without a predicate: in this case they just check the collection emptiness. any() returns true if there are elements and false if there aren’t; none() does the opposite.