The method partition
is available in Kotlin for arrays and iterable objects to split it into two lists.
We pass a predicate lambda function to the partition
method.
The predicate should return either true
or false
based on a condition for each element from the array or iterable.
The return result is a Pair
instance where the first element is a List
object with all elements that returned true
from the predicate.
The second element in the Pair
object contains all elements for which the predicate returned false
.
As a String
can be seen as an iterable of characters we can also use partition
on a String
instance.
In the following example code we use partition on different objects:
// Create an infinite sequence of increasing numbers. val numbers = generateSequence(0) { i -> i + 1 } // We take the first 20 numbers from our sequence and // partition it to two pairs. // First element of the pair is a list of all even numbers, // second element is the list of all odd numbers. // We use destructurizing to assign the pair values to // variables even and odd. val (even, odd) = numbers.take(20) .partition { n -> n % 2 == 0} assert(even == listOf(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)) assert(odd == listOf(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)) // Sample map with data. val data = mapOf("language" to "Java", "username" to "mrhaki", "age" to 49) // We can also use partition on the entries of the map. val (stringValues, nonStringValues) = data.entries.partition { entry -> entry.value is String } assert(stringValues.associate { it.toPair() } == mapOf("language" to "Java", "username" to "mrhaki")) assert(nonStringValues.associate { it.toPair() } == mapOf("age" to 49)) // Sample string to use with partition. val s = "Kotlin kandy!" // We can also use partition on a string where // the predicate is applied for each character. val (letters, others) = s.partition(Char::isLetter) assert(letters == "Kotlinkandy") assert(others == " !")
Written with Kotlin 1.7.20.