Kotlin partition() Method with Examples
Last Updated :
15 Mar, 2022
In this article, we are going to discuss how to split the original collection into pair of collections, because sometimes while coding, you wish that you could just split a list into sublists without going into the for and while loops. Kotlin provides you with a function just for this occasion. In this article, we will see how to split a list based on some criteria. Suppose there is a list on which you need to perform an operation to segregate its items into two lists, one which agrees to some condition and the other which doesn’t. The typical way to do this is to run a loop over the collection object and add an if condition inside and segregate the object.
Kotlin
val list = listOf(1 , 2, 3, 4, 5)
val evenList = mutableListOf<Int>()
val oddList = mutableListOf<Int>()
for(item in list){
if(item % 2 == 0){
evenList.add(item)
} else {
oddList.add(item)
}
}
println(evenList)
println(oddList)
Kotlin has something in inbuild, which can make your life easier. There is an operator caller partition() that can segregate the list into two lists, one with the items matching the condition and another one with the non-matching condition, and the code will be like this:
Kotlin
val list = listOf(1 , 2, 3, 4, 5)
val (even, odd) = list.partition { it % 2 == 0}
println(even)
println(odd)
Kotlin provides a partition function. According to the documentation of the partition function, it does the following, Splits the original array into a pair of lists, where the first list contains elements for which predicate yielded true, while the second list contains elements for which predicate yielded false.
Example 1:
In this example, we will create a list of numbers, and we want to split this list into two sublists: one having odd numbers and the other having even numbers:
Kotlin
fun main (args: Array<String>){
val listA= listof (1, 2, 3, 4, 5, 6)
val pair = listA.partition {
it%2==0
}
println(pair)
}
Output:
( [2, 4, 6], [1, 3, 5])
As you can see in the preceding example, we need to put the condition in the predicate inside the partition block. The returned object is a Pair object, holding the two sublists. The partition function also works with the set collection in a similar way:
Kotlin
val setA= setof (1, 2, 3, 4, 5, 6)
val pair= setA.partition{
it$2-=0
}
printin (pair)
Output:
([2, 4, 6], [1, 3, 5])
Explanation:
Let's take a look at the implementation of the partition function in Kotlin:
Kotlin
public inline fun <T> Iterable<T> .partition (predicate: (T) -> Boolean) :
Pair<List<T>, List<T>>{
val first = ArrayList<T>()
val second = ArrayList <T> ()
for (element in this) {
if (predicate (element) ) {
first.add (element)
} else {
second.add(element)
}
}
return Pair (first, second)
}
As you can see, the partition function is just an abstraction, that saves you from writing long for loops, but internally it does it the same old way.
Example 2:
The partition function works in a similar way with arrays as well. Here are its different usages. Each of them works similarly, just producing lists of different types:
Kotlin
// Produces two lists
inline fun <T> Array< out T>.partition(
predicate: (T) -> Boolean
): Pair<List<T>, List<T>>
// Breaks original list of Byte
// and produces two lists of Byte
inline fun ByteArray.partition(
predicate: (Byte) -> Boolean
): Pair<List<Byte>, List<Byte>>
// Breaks original list of Short
// and produces two lists of Short
inline fun ShortArray.partition(
predicate: (Short) -> Boolean
): Pair<List<Short>, List<Short>>
// Breaks original list of Int
// and produces two lists of Int
inline fun IntArray.partition(
predicate: (Int) -> Boolean
): Pair<List<Int>, List<Int>>
// Breaks original list of Long
// and produces two lists of Long
inline fun LongArray.partition(
predicate: (Long) -> Boolean
): Pair<List<Long>, List<Long>>
// Breaks original list of Float
// and produces two lists of Float
inline fun FloatArray.partition(
predicate: (Float) -> Boolean
): Pair<List<Float>, List<Float>>
// Breaks original list of Double
// and produces two lists of Double
inline fun DoubleArray.partition (
predicate: (Double) -> Boolean
): Pair<List<Double>, List<Double>>
// Breaks original list of Boolean
// and produces two lists of Boolean
inline fun BooleanArray.partition (
predicate: (Boolean) -> Boolean
): Pair<List<Boolean>, List<Boolean>>
// Breaks original list of Char
// and produces two lists of Char
inline fun CharArray.partition (
predicate: (Char) -> Boolean
): Pair<List<Char>, List<Char>>
Similar Reads
Kotlin Function Variations With Examples
While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
3 min read
Kotlin Collection Write operations
Collection Write operations are used to change the content of MutableCollection. MutableCollection is defined as the Collection with write operations like add and remove. Operations supported are as follows: Adding elements Removing elements and Updating elements Addition of elements - add() functio
4 min read
Kotlin Aggregate operations
Aggregate operation is an operation that is performed on a data structure, such as an array, as a whole rather than performed on an individual element. Functions that used aggregate operations are as follows: count() function is used to returns the number of elements. sum() function is used to retur
5 min read
Kotlin - Collection Operations Overview
Kotlin provides a rich set of tools for working with collections like lists, sets, and maps. Whether you want to add, remove, sort, filter, or transform data, Kotlinâs standard library makes it easy and expressive.Two Ways Kotlin Defines Collection FunctionsCollection operations are declared in two
4 min read
Named Parameters in Kotlin
A parameter is a value that you can pass to a method. Then the method can use the parameter as though it were a local variable initialized with the value of the variable passed to it by the calling method. Function parameters are defined using Pascal notation - name: type. Parameters are separated u
3 min read
Multiconditional Loop in Kotlin
As we all know about loops, in Kotlin, loops are compiled down to optimized loops wherever possible. For example, if you iterate over a number range, the bytecode will be compiled down to a corresponding loop based on plain int values to avoid the overhead of object creation. Conditional loops are c
3 min read
Kotlin Collections Ordering
There are certain collections where the order of the elements is important. If you take lists, two lists are never equal if they are ordered differently inspite of having same elements.In Kotlin, there are different ways of ordering the elements. Most built-in types are comparable: -Numeric types fo
3 min read
Kotlin | Collection Transformation
Kotlin standard library provides different set of extension functions for collection transformations. These functions help in building new collections from existing collections based on the rules defined by the transformation. There are different number of transformation functions:  MappingZippingA
5 min read
Returns, Jumps and Labels in Kotlin
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is an object-oriented language, and a âbetter lan
3 min read
Android App Development with Kotlin: A Technical Overview
Android Kotlin app development is a popular way to create mobile applications for the Android platform. Kotlin is a modern programming language that is designed to be easy to use and understand, making it a great choice for developers who want to create apps quickly and efficiently. In this article,
7 min read