Kotlin List partition()
Syntax & Examples


Syntax of List.partition()

The syntax of List.partition() extension function is:

fun <T> Iterable<T>.partition( predicate: (T) -> Boolean ): Pair<List<T>, List<T>>

This partition() extension function of List splits the original collection into pair of lists, where first list contains elements for which predicate yielded true, while second list contains elements for which predicate yielded false.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the partition() function with a predicate to split the list into two lists based on even and odd numbers.
  • We destructure the resulting pair into even and odd lists.
  • We then print the even and odd numbers using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val (even, odd) = list.partition { it % 2 == 0 }
    println("Even numbers: $even")
    println("Odd numbers: $odd")
}

Output

Even numbers: [2, 4]
Odd numbers: [1, 3, 5]

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c', 'e', 'i', 'o', 'u'.
  • We use the partition() function with a predicate to split the list into vowels and consonants.
  • We destructure the resulting pair into vowels and consonants lists.
  • We then print the vowels and consonants using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c', 'e', 'i', 'o', 'u')
    val (vowels, consonants) = list.partition { it in "aeiou" }
    println("Vowels: $vowels")
    println("Consonants: $consonants")
}

Output

Vowels: [a, e, i, o, u]
Consonants: [b, c]

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry", "orange".
  • We use the partition() function with a predicate to split the list into short and long words based on their lengths.
  • We destructure the resulting pair into short and long lists.
  • We then print the short and long words using println().

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "orange")
    val (short, long) = list.partition { it.length <= 5 }
    println("Short words: $short")
    println("Long words: $long")
}

Output

Short words: [apple]
Long words: [banana, cherry, orange]

Summary

In this Kotlin tutorial, we learned about partition() extension function of List: the syntax and few working examples with output and detailed explanation for each example.