Sunday 18 April 2021

Kotlin - Partition Function

Splits the original array / collections into pair of lists, where first list contains elements for which predicate yielded true, while second list contains elements for which predicate yielded false.

Please refer the below examples, here we used 2 filters to get the objects with certain crieteria, but it can be easily achieved through partition function, this executes the predicate and produce the pairs of list and we can access directly on pari's (first and second function) or we can destructure and use the same. 

data class Movies(val id: String,
                      val movieName: String,
                      val rating: Double = 1.0)

    val movies = listOf(Movies("100XA", "Guru", 4.5),
            Movies("100JK", "Ghab", 3.2),
            Movies("100HN", "Qualis", 1.2),
            Movies("1089O", "Tree"))

    // Using Filter
    println("### Rating Above 3 - Filter ###")
    movies.filter { it.rating > 3 }.forEach { println(it.movieName) }

    println("### Rating Not Above 3 - Filter ###")
    movies.filterNot { it.rating > 3 }.forEach { println(it.movieName) }

    // Using Partition - Destructuring the paris of list
    val (above3, notAbove3) = movies.partition { it.rating > 3 }
    println("\n### Rating Above 3 - Partition  ###")
    above3.forEach { println(it.movieName) }

    println("### Rating Not Above 3 - Partition  ###")
    notAbove3.forEach { println(it.movieName) }

Output:

### Rating Above 3 - Filter ###
Guru
Ghab
### Rating Not Above 3 - Filter ###
Qualis
Tree

### Rating Above 3 - Partition  ###
Guru
Ghab
### Rating Not Above 3 - Partition  ###
Qualis
Tree

No comments: