Kotlin Array - partition() Function



The Kotlin array partition() function is used to split the elements of an array into two separate sequences: the first sequence contains the elements that satisfy a specified predicate (i.e., are true) and the second sequence contains the elements that do not satisfy the given predicate (i.e., are false).

Syntax

Following is the syntax of Kotlin array partition() function −

fun String.partition(
   predicate: (Char) -> Boolean
): Pair<String, String>

Parameters

This function accepts predicate as a parameter.

Return value

This function returns a boolean value.

Example 1

The following is a basic example to demonstrate the use of partition() function −

fun main(args: Array<String>) {
   var array = arrayOf<Int>(1, 2, 3, 4, 5, 6, 7, 8)
      
   val result = array.partition({it%2==0})
   
   println("Split pair: $result")
}

Output

The above code produce following output −

Split pair: ([2, 4, 6, 8], [1, 3, 5, 7])

Example 2

Now, let's create another example. Here, we have an string. We then use partition() to split the vowel and consonant into different sequences −

fun main(args: Array<String>) {
   // by default ignore care is true
   fun isVowel(c: Char) = "aeuio".contains(c, ignoreCase = true)
   
   val string = "tutorialspoint"    
   val result = string.partition(::isVowel)
   
   println("Split pair: $result")
}

Output

Following is the output −

Split pair: (uoiaoi, ttrlspnt)

Example 3

The below example uses the partition function to separate the string having length greater than 5 −

fun main(args: Array<String>) {
   var array = arrayOf<String>("Hello", "tutorialspoint", "India", "Pvt", "ltd")
   val strings = array.partition({it.length>4});
   println("$strings")   
}

Output

Following is the output −

([Hello, tutorialspoint, India], [Pvt, ltd])
kotlin_arrays.htm
Advertisements