🎓 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
In this guide, you will learn how to use the map function in Kotlin with examples.
What is List Mapping in Kotlin?
Mapping is the process of transforming each element in a list based on a given function. The result is a new list where each item is the outcome of applying this function to the original item.
Basic Syntax:
fun <T, R> List<T>.map(transform: (T) -> R): List<R>Examples with Output
Basic Mapping
Converting a list of numbers to their string representations:val numbers = listOf(1, 2, 3)
val asStrings = numbers.map { it.toString() }
println(asStrings) // Output: [1, 2, 3]Mapping with Index
Sometimes, you might need the index of an element during the transformation:
val words = listOf("apple", "banana", "cherry")
val indexedWords = words.mapIndexed { index, word -> "$index: $word" }
println(indexedWords) // Output: [0: apple, 1: banana, 2: cherry]Mapping Custom Objects
Consider mapping a list of Person objects to retrieve their names:
data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 30), Person("Bob", 25))
val names = people.map { it.name }
println(names) // Output: [Alice, Bob]Nested Mapping
When dealing with nested lists or objects, you can use nested mappings:
data class Classroom(val name: String, val students: List<Student>)
data class Student(val name: String, val grade: Int)
val classrooms = listOf(
Classroom("A1", listOf(Student("John", 90), Student("Doe", 85))),
Classroom("B2", listOf(Student("Jane", 92), Student("Smith", 88)))
)
val averageGrades = classrooms.map { classroom ->
val average = classroom.students.map { it.grade }.average()
"$${classroom.name}: $average"
}
println(averageGrades) // Output: [A1: 87.5, B2: 90.0]Combining map with Other List Operations
Chain map with other transformations for more complex manipulations:
val numbers = listOf(1, 2, 3, 4, 5)
val squaredEvens = numbers.filter { it % 2 == 0 }.map { it * it }
println(squaredEvens) // Output: [4, 16]Why and When to Use map
Data Transformation: Whenever you need to transform every element in a collection based on a certain rule or function, the map function is your go-to utility.
Data Extraction: For extracting specific properties from a list of objects.
Composing Operations: map can be combined with other list functions for more intricate manipulations.
Caveats
Remember that the map function, like other transformation functions in Kotlin's standard library, returns a new list and doesn't modify the original list.
For large data sets or intensive operations, consider utilizing Kotlin sequences (asSequence()) to achieve lazy evaluations, enhancing efficiency.
Conclusion
Kotlin's map function provides a succinct and powerful mechanism to transform collections. With the provided examples as a foundation, you're well-equipped to wield map function in your Kotlin projects, enhancing both your code's clarity and efficiency. Happy mapping!
Related Kotlin Posts
- Kotlin List
- Kotlin Set
- Kotlin listOf
- Kotlin mutableListOf
- Kotlin mapOf
- Kotlin mutableMapOf
- Kotlin setOf
- Kotlin mutableSetOf
- Kotlin sequenceOf
- Kotlin list filter
- Kotlin list map
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