Skip to content
Related Articles

Related Articles

Kotlin | Filtering Collections
  • Last Updated : 05 Sep, 2019

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.

  • There are standard library contains number of functions that let you filter the collections in a single call.
  • These functions don’t change the contents of the original collection or available for immutable and mutable both.
  • We can assign it to a variable or chain the functions after filtering to operate the filtering result.

Filtering by predicates –

  • The basic function is filter() to be used for filtering.
  • When filter() function is called with a predicate, it returns the collection elements that match the predicate.
  • For List and Set, the resulting collection is also List but for Map it will return Map.

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()

  • If we want to filter using element index or position, we have to use filterIndexed().
  • filterIndexed() function takes a predicate with two arguments: index and the value of an element.
  • We can filter the collections by negative conditions by using filterNot().

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:

  • any() : It returns true if atleast one element matches the given predicate.
  • none() : It returns true if none of the elements match the given predicate.
  • all() : It returns true if all the elements of the collection match the given predicate.

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","helo","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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :