Kotlin filter Function | Filter Elements of Collection by Condition in Kotlin

The filter function in Kotlin is used to filter elements of a collection based on a given predicate. This function belongs to the Kotlin standard library and provides a way to create a new list containing only the elements that match the specified condition.

Table of Contents

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

Introduction

The filter function allows you to filter elements of a collection (such as a list) based on a given predicate. The resulting list contains only the elements that match the specified condition. This function is useful for extracting specific elements from a collection based on custom criteria.

filter Function Syntax

The syntax for the filter function is as follows:

fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>

Parameters:

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

Returns:

  • A new list containing only the elements that match the specified predicate.

Understanding filter

The filter function iterates over each element in the collection and applies the given predicate to it. If the predicate returns true, the element is included in the resulting list; otherwise, it is excluded. This allows you to create a subset of the original collection based on specific criteria.

Examples

Basic Usage

To demonstrate the basic usage of filter, we will filter a list of integers to include only even numbers.

Example

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

Output:

Even numbers: [2, 4, 6]

Filtering a List of Strings

This example shows how to use filter to create a new list containing only strings that meet a certain condition.

Example

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "date")
    val longFruits = fruits.filter { it.length > 5 }
    println("Fruits with more than 5 characters: $longFruits")
}

Output:

Fruits with more than 5 characters: [banana, cherry]

Filtering with Custom Conditions

This example demonstrates how to use filter with custom conditions to filter 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)
    )
    val adults = people.filter { it.age >= 30 }
    println("Adults: $adults")
}

Output:

Adults: [Person(name=Alice, age=30), Person(name=Charlie, age=35)]

Real-World Use Case

Filtering a List of Orders

In real-world applications, the filter function can be used to filter a list of orders based on their status or other criteria.

Example

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

fun main() {
    val orders = listOf(
        Order(1, 100.0, "Shipped"),
        Order(2, 150.0, "Pending"),
        Order(3, 200.0, "Shipped")
    )
    val shippedOrders = orders.filter { it.status == "Shipped" }
    println("Shipped orders: $shippedOrders")
}

Output:

Shipped orders: [Order(id=1, amount=100.0, status=Shipped), Order(id=3, amount=200.0, status=Shipped)]

Conclusion

The filter function in Kotlin is a powerful and convenient way to create a new list containing only the elements that match a specified predicate. It allows you to easily extract specific elements from a collection based on custom criteria, making it useful for various applications, including data processing, filtering user input, and more. 

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

Comments