partition() : Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/partition-kotlin/ and reposted on Medium on 23rd Oct 2019.
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)
val list = listOf(1 , 2, 3, 4, 5)
val (even, odd) = list.partition{ it % 2 == 0}

println(even)
println(odd)
/**
* Splits the original collection into pair of lists,
* where *first* list contains elements for which [predicate] yielded `true`,
* while *second* list contains elements for which [predicate] yielded `false`.
*/
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)
}

--

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal

https://agrawalsuneet.github.io/

More from Medium

Cancelling Kotlin Coroutines

How to Use TriState Toggle in Jetpack Compose

Fused Location Provider in Kotlin

Intro to Jetpack Compose