Kotlin partition Function | Split Lists into Two Groups by Condition in Kotlin

The partition function in Kotlin is used to split a collection into two lists based on a given predicate. This function belongs to the Kotlin standard library and provides a convenient way to separate elements that match a given condition from those that do not.

Table of Contents

  1. Introduction
  2. partition Function Syntax
  3. Understanding partition
  4. Examples
    • Basic Usage
    • Partitioning a List of Strings
    • Partitioning with Custom Conditions
  5. Real-World Use Case
  6. Conclusion

Introduction

The partition function allows you to split elements of a collection (such as a list) into two lists based on a given predicate. The resulting pair contains two lists: the first list contains elements that match the predicate, and the second list contains elements that do not match the predicate. This is useful for scenarios where you need to categorize or partition elements based on specific criteria.

partition Function Syntax

The syntax for the partition function is as follows:

fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>>

Parameters:

  • predicate: A lambda function that takes an element of the original collection as input and returns true if the element should be included in the first list, and false otherwise.

Returns:

  • A pair of lists, where the first list contains elements that match the predicate, and the second list contains elements that do not match the predicate.

Understanding partition

The partition function iterates over each element in the original collection, applies the given predicate to it, and adds the element to one of the two resulting lists based on whether the predicate returns true or false. This allows you to separate elements based on specific criteria.

Examples

Basic Usage

To demonstrate the basic usage of partition, we will split a list of integers into even and odd numbers.

Example

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val (evenNumbers, oddNumbers) = numbers.partition { it % 2 == 0 }
    println("Even numbers: $evenNumbers")
    println("Odd numbers: $oddNumbers")
}

Output:

Even numbers: [2, 4, 6]
Odd numbers: [1, 3, 5]

Partitioning a List of Strings

This example shows how to use partition to split a list of strings based on their length.

Example

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "date", "fig", "grape")
    val (longFruits, shortFruits) = fruits.partition { it.length > 4 }
    println("Long fruits: $longFruits")
    println("Short fruits: $shortFruits")
}

Output:

Long fruits: [apple, banana, cherry, grape]
Short fruits: [date, fig]

Partitioning with Custom Conditions

This example demonstrates how to use partition with custom conditions to split a list of objects.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = listOf(
        Person("Alice", 30),
        Person("Bob", 25),
        Person("Charlie", 35),
        Person("David", 20)
    )
    val (adults, minors) = people.partition { it.age >= 30 }
    println("Adults: $adults")
    println("Minors: $minors")
}

Output:

Adults: [Person(name=Alice, age=30), Person(name=Charlie, age=35)]
Minors: [Person(name=Bob, age=25), Person(name=David, age=20)]

Real-World Use Case

Filtering and Partitioning Orders by Amount

In real-world applications, the partition function can be used to filter and partition orders based on their amount, allowing you to separate high-value orders from low-value orders.

Example

data class Order(val id: Int, val amount: Double)

fun main() {
    val orders = listOf(
        Order(1, 100.0),
        Order(2, 150.0),
        Order(3, 50.0),
        Order(4, 200.0),
        Order(5, 75.0)
    )
    val (highValueOrders, lowValueOrders) = orders.partition { it.amount >= 100.0 }
    println("High-value orders: $highValueOrders")
    println("Low-value orders: $lowValueOrders")
}

Output:

High-value orders: [Order(id=1, amount=100.0), Order(id=2, amount=150.0), Order(id=4, amount=200.0)]
Low-value orders: [Order(id=3, amount=50.0), Order(id=5, amount=75.0)]

Conclusion

The partition function in Kotlin is a powerful and convenient way to split elements of a collection into two lists based on a specified predicate. It allows you to categorize and separate elements, making it useful for various applications, including data processing, categorization, and organization. 

By understanding and using the partition function, you can effectively manage and split collections in your Kotlin applications.

Comments