Open In App

Kotlin | Filtering Collections

In Kotlin, filtering is a prominent task of collection processing. The filtering conditions are defined by predicates – lambda functions that take a collection element and return true when the given element matches the predicate, and false means it doesn’t match the predicate. 
 

 



Filtering by predicates –

 

Kotlin program of using the filter function on list and Map collection – 
 






fun main(args: Array<String>)
{
    //declaring a list of elements
    val list = listOf("geeks","for","geeks","hello","world")
  
    //filtering all words with length > 4
    val longerThan4 = list.filter { it.length > 4 }
    println(longerThan4)
 
    //declaring a map of string to integers
    val numbersMap = mapOf("key13" to 10, "key25" to 20,
        "key34" to 30, "key45" to 40, "key55" to 50 )
 
    //filtering the map with some predicates
    val filteredMap = numbersMap.filter { (key, value) ->
        key.endsWith("5") && value > 20}
    println(filteredMap)
}

Output: 
 

[geeks, geeks, hello, world]
{key45=40, key55=50}

 

Variations in filter()

 

Kotlin program of using the filterIndexed() and filterNot() functions – 
 




fun main(args: Array<String>) {
    val words = listOf("geek","for","geeks","all","world")
 
    //filtering a list by : words having length < 6 and index != 0
    val filteredIndex = words.filterIndexed { index, s ->
        (index != 0) && (s.length < 6)  }
 
    //filtering words having length >=3 using filterNot
    val filteredNot = words.filterNot { it.length <= 3 }
 
    println(filteredIndex)
    println(filteredNot)
}

Output: 
 

[for, geeks, all, world]
[geek, geeks, world]

 

Partitioning –

There is another filtering function partition() which filters a collection by a predicate and separates all the elements, which don’t match the predicate and put in a different list. 
Basically, it returns a pair of list: the first list containing the elements that match the predicate and the second list contains all the element from the original collection which don’t match the predicate.
Kotlin program of using partitioning – 
 




fun main(args: Array<String>) {
 
    val words = listOf("geek","for","geeks","hello","world")
 
    //partitioning the words by length > 4 and length <= 4
    val (first, second) = words.partition { it.length > 4 }
 
    println(first)
    println(second)
}

Output: 
 

[geeks, hello, world]
[geek, for]

 

Testing predicates –

Some of the functions to test a predicate against the collection elements are following: 
 

Note: all() returns true when called with any valid predicate on an empty collection. This is known as vacuous truth
We can use any() and none() without a predicate, it will just check for the emptiness of the collection, i.e. any() will return true if collection has elements and false if its empty; none() do just opposite of any().
Kotlin program of using any(), none() and all() functions – 
 




fun main(args: Array<String>) {
    val words = listOf("geeks","for","geeeks","hello","world")
 
    //checking if atleast one word ends with s or not
    println("Any element matches? "+words.any { it.endsWith("s") })
 
    //checking if no word ends with a or not
    println("No element matches? "+words.none { it.endsWith("a") })
 
    println("All element match? "+words.all { it.endsWith("d") })
    //checking if all words end with d or not
 
    //when predicate is empty, it checks for emptiness
    println(words.any())
    println(words.none())
 
    //all function on an empty list
    println(emptyList<Int>().all { it > 5 })   // vacuous truth
 
    val empty = emptyList<String>()
 
    //any function on an empty list returns false
    println(empty.any())
    //none function on an empty list returns true
    println(empty.none())
}

Output: 
 

Any element matches? true
No element matches? true
All element match? false
true
false
true
false
true

 


Article Tags :