0
0
Kotlinprogramming~5 mins

Partition for splitting in Kotlin

Choose your learning style9 modes available
Introduction
Partition helps you split a list into two groups based on a rule, making it easy to separate items you want from those you don't.
When you want to separate even and odd numbers from a list.
When you need to split a list of names into those starting with a certain letter and those that don't.
When filtering a list into items that meet a condition and those that don't, but want to keep both groups.
When organizing data into two categories quickly without writing loops.
Syntax
Kotlin
val (group1, group2) = list.partition { condition }
The condition inside the curly braces is a rule that returns true or false for each item.
group1 contains items where the condition is true, group2 contains the rest.
Examples
Splits numbers into even and odd lists.
Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val (evens, odds) = numbers.partition { it % 2 == 0 }
Splits names into those starting with 'A' and others.
Kotlin
val names = listOf("Anna", "Bob", "Alice", "Brian")
val (aNames, otherNames) = names.partition { it.startsWith("A") }
Sample Program
This program splits a list of fruits into those starting with 'a' and the rest, then prints both groups.
Kotlin
fun main() {
    val fruits = listOf("apple", "banana", "avocado", "blueberry", "apricot")
    val (aFruits, otherFruits) = fruits.partition { it.startsWith("a") }
    println("Fruits starting with 'a': $aFruits")
    println("Other fruits: $otherFruits")
}
OutputSuccess
Important Notes
Partition returns a Pair of lists, so you can use destructuring to get both groups easily.
The original list is not changed; partition creates new lists.
Use partition when you want both groups, not just filtered items.
Summary
Partition splits a list into two lists based on a condition.
It returns a Pair where the first list has items matching the condition.
Use it to separate data quickly without loops.