Kotlin Array filter Function

The filter function in Kotlin is used to select elements from an array that satisfy a given predicate. This function is part of the Kotlin standard library and provides a powerful way to filter elements in an array based on a condition.

Table of Contents

  1. Introduction
  2. filter Function Syntax
  3. Understanding filter
  4. Examples
    • Basic Usage
    • Using filter with Custom Types
    • Filtering Null Values
    • Chaining filter and map Functions
  5. Real-World Use Case
  6. Conclusion

Introduction

The filter function returns a new list containing only the elements of the original array that match the specified condition. It is a simple and effective way to create a subset of an array based on a predicate.

filter Function Syntax

The syntax for the filter function is as follows:

inline fun <T> Array<out T>.filter(predicate: (T) -> Boolean): List<T>

Parameters:

  • predicate: A lambda function that takes an element of type T and returns a boolean indicating whether the element should be included in the result.

Returns:

  • A list containing the elements that match the predicate.

Understanding filter

The filter function is used to create a new list by selecting elements from an array that satisfy a given condition. This is particularly useful for extracting relevant data from a collection.

Examples

Basic Usage

To demonstrate the basic usage of filter, we will create an array of integers and filter out the even numbers.

Example

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

Output:

Even numbers: [2, 4, 6, 8, 10]

Using filter with Custom Types

This example shows how to use filter to select elements from an array of custom objects based on a condition.

Example

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

fun main() {
    val people = arrayOf(
        Person("Ravi", 25),
        Person("Anjali", 30),
        Person("Priya", 22),
        Person("Rahul", 28),
        Person("Amit", 19)
    )

    val adults = people.filter { it.age >= 21 }
    println("Adults: $adults")
}

Output:

Adults: [Person(name='Ravi', age=25), Person(name='Anjali', age=30), Person(name='Priya', age=22), Person(name='Rahul', age=28)]

Filtering Null Values

This example demonstrates how to use filter to remove null values from an array of nullable types.

Example

fun main() {
    val numbers = arrayOf(1, 2, null, 4, 5, null, 7)
    val nonNullNumbers = numbers.filter { it != null }
    println("Non-null numbers: $nonNullNumbers")
}

Output:

Non-null numbers: [1, 2, 4, 5, 7]

Chaining filter and map Functions

This example shows how to chain the filter and map functions to filter and transform elements in an array.

Example

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val doubledEvenNumbers = numbers.filter { it % 2 == 0 }
                                    .map { it * 2 }
    println("Doubled even numbers: $doubledEvenNumbers")
}

Output:

Doubled even numbers: [4, 8, 12, 16, 20]

Real-World Use Case

Filtering Data Based on Criteria

In real-world applications, the filter function can be used to extract relevant data from a collection based on specific criteria, such as filtering a list of users based on their age or status.

Example

data class User(val id: Int, val username: String, val isActive: Boolean)

fun main() {
    val users = arrayOf(
        User(1, "user1", true),
        User(2, "user2", false),
        User(3, "user3", true),
        User(4, "user4", false),
        User(5, "user5", true)
    )

    val activeUsers = users.filter { it.isActive }
    println("Active users: $activeUsers")
}

Output:

Active users: [User(id=1, username=user1, isActive=true), User(id=3, username=user3, isActive=true), User(id=5, username=user5, isActive=true)]

Conclusion

The filter function in Kotlin is used for selecting elements in an array that satisfy a given condition. It allows you to create a subset of an array based on a predicate, making it useful for data extraction and manipulation. By understanding and using this function, you can effectively manage data filtering in your Kotlin applications.

Comments