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 – 
 

Java




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]

 

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 –

...