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 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
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
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
Kotlin | Retrieve Collection Parts The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying th
5 min read
Kotlin list : Arraylist The ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as a prerequisite. It also provides read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature. We use ArrayList to acce
6 min read
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Destructuring Declarations in Kotlin Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables corresp
3 min read
A Complete Guide to Learn Kotlin For Android App Development Kotlin is a statically typed, cross-platform, general-purpose programming language for JVM developed by JetBrains. This is a language with type inference and fully interoperable with Java. Kotlin is concise and expressive programming as it reduces the boilerplate code. Since Google I/O 2019, Android
8 min read
Kotlin for loop In Kotlin, the for loop is equivalent to the foreach loop of other languages like C#. Here for loop is used to traverse through any data structure that provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of the for loop in Kot
4 min read
Kotlin Collections In Kotlin, collections are used to store and manipulate groups of objects or data. There are several types of collections available in Kotlin, including:Collection NameDescriptionLists Ordered collections of elements that allow duplicates.Sets Unordered collections of unique elements.Maps Collection
6 min read