0
0
Kotlinprogramming~30 mins

GroupBy for categorization in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
GroupBy for categorization
📖 Scenario: You work in a bookstore. You have a list of books with their genres. You want to group the books by their genre to organize the store better.
🎯 Goal: Build a Kotlin program that groups a list of books by their genre using groupBy.
📋 What You'll Learn
Create a list of books with exact titles and genres
Create a variable to hold the grouped books
Use groupBy to group books by genre
Print the grouped books
💡 Why This Matters
🌍 Real World
Grouping items by categories is common in organizing data, like sorting books by genre in a bookstore.
💼 Career
Understanding how to group data helps in data analysis, reporting, and building features like filters in apps.
Progress0 / 4 steps
1
Create the list of books
Create a list called books with these exact entries: "The Hobbit" to "Fantasy", "1984" to "Dystopian", "The Catcher in the Rye" to "Classic", "The Lord of the Rings" to "Fantasy", and "Brave New World" to "Dystopian".
Kotlin
Need a hint?

Use listOf with pairs of book title and genre using to.

2
Create a variable for grouped books
Create a variable called groupedBooks to hold the result of grouping books by genre.
Kotlin
Need a hint?

Use groupBy on books and group by the genre, which is the second element of each pair.

3
Group books by genre using groupBy
Use groupBy on books with a lambda that selects the genre (the second element) to group the books. Store the result in groupedBooks.
Kotlin
Need a hint?

The grouping is done by the genre, which is the second part of each pair.

4
Print the grouped books
Print the groupedBooks variable to show the books grouped by genre.
Kotlin
Need a hint?

Use println(groupedBooks) to display the grouped map.