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 – 
 

Java




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]

 

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. 
 

  • 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.

 

Similar Reads

Filtering by predicates –

...

Variations in filter()

...

Partitioning –

...

Testing predicates –

...