🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
filterFunction Syntax- Understanding
filter - Examples
- Basic Usage
- Using
filterwith Custom Types - Filtering Null Values
- Chaining
filterandmapFunctions
- Real-World Use Case
- 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 typeTand 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment