0
0
Kotlinprogramming~15 mins

FlatMap for nested collections in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
FlatMap for nested collections
📖 Scenario: You work at a bookstore that organizes books by genre. Each genre has a list of book titles. You want to create a single list of all book titles from all genres.
🎯 Goal: Build a Kotlin program that uses flatMap to combine nested lists of book titles into one flat list.
📋 What You'll Learn
Create a map called booksByGenre with genres as keys and lists of book titles as values
Create a variable called allBooks that uses flatMap on booksByGenre.values
Print the allBooks list
💡 Why This Matters
🌍 Real World
Bookstores and libraries often organize books by categories. Combining all books into one list helps with searching and displaying all available titles.
💼 Career
Understanding how to flatten nested collections is useful in data processing, backend development, and anywhere you handle grouped data.
Progress0 / 4 steps
1
Create the nested data structure
Create a map called booksByGenre with these exact entries: "Fiction" to listOf("The Alchemist", "1984"), "Science" to listOf("A Brief History of Time", "The Selfish Gene"), and "History" to listOf("Sapiens", "Guns, Germs, and Steel").
Kotlin
Need a hint?

Use mapOf to create a map with string keys and list values.

2
Prepare to flatten the nested lists
Create a variable called allBooks and set it to booksByGenre.values. This will get all the lists of books from the map.
Kotlin
Need a hint?

Use booksByGenre.values to get all the lists of books.

3
Use flatMap to combine all book lists
Change the allBooks variable to use flatMap on booksByGenre.values to create a single list of all book titles. Use flatMap { it } to flatten the lists.
Kotlin
Need a hint?

Use flatMap { it } to flatten the nested lists into one list.

4
Print the combined list of books
Write a println statement to print the allBooks list.
Kotlin
Need a hint?

Use println(allBooks) to show the combined list.