Partition function in Kotlin

Hardik VegadHardik Vegad
2 min read

A Deep Dive into the Versatile Partition Function of Kotlin

As developers, we're no strangers to the challenges of managing and organizing data efficiently. Whether you're an experienced Kotlin developer or new to the language, knowing how to use the Partition function can make a big difference in simplifying tricky tasks involving sorting and organizing data.

Join me as we explore Kotlin's Partition function, Let's get started.

What is Partition Function?

In Kotlin a Partition function helps to split the passed collection into a pair of lists, In the list the first element will be the predicate yielded true value, while the other will be the value yielded false.

In simple words this operator caller partition() can segregate the list, one part with the items that match the condition and another with the non-matching condition.

Let's write some code

A data class Movie having fields id, name, and type,

data class Movie(
    val id: Int,
    val name: String, 
    val type: MovieType
)

Now let's create an enum class MovieType,

enum class MovieType{
  HOLLYWOOD, BOLLYWOOD
}

We will use the partition function on a list so let's create a list of Movies.

val movies = listOf(
  Movie(1, "Tejas", MovieType.BOLLYWOOD),
  Movie(2, "12th Fail", MovieType.BOLLYWOOD),
  Movie(3, "Top Gun", MovieType.HOLLYWOOD),
  Movie(4, "3 Idiots", MovieType.BOLLYWOOD),
  Movie(5, "Godzilla", MovieType.HOLLYWOOD),
  Movie(6, "The Aviator", MovieType.HOLLYWOOD),
)

Now, let's use the partition function on this list of movies to filter the movies from Bollywood and those that are not.

val partitioned = movies.partition { it.type == MovieType.BOLLYWOOD }
println("Bollywood: ${partitioned.first}")
println("Hollywood: ${partitioned.second}")

Run the code and see the output:

Bollywood: [Movie(id=1, name=Tejas, type=BOLLYWOOD), Movie(id=2, name=12th Fail, type=BOLLYWOOD), Movie(id=4, name=3 Idiots, type=BOLLYWOOD)]
Hollywood: [Movie(id=3, name=Top Gun, type=HOLLYWOOD), Movie(id=5, name=Godzilla, type=HOLLYWOOD), Movie(id=6, name=The Aviator, type=HOLLYWOOD)]

There is an addition to the partition function that is destructuring. Let's see how it works.

val (bollywoodMovies, hollywoodMovies) = movies.partition { it.type == MovieType.BOLLYWOOD}
println("Bollywood: $bollywoodMovies")
println("Hollywood: $hollywoodMovies")

You will get the same output, But we have a more convenient way to use the destructuring here.

I hope this article helps you understand the concept.

2
Subscribe to my newsletter

Read articles from Hardik Vegad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hardik Vegad
Hardik Vegad