Kotlin Collections Explained: List, Set, Map & Collection Operations

When developing Android applications using Kotlin and Jetpack Compose, we frequently work with groups of data.

For example:

  • Displaying a list of users
  • Managing products in a shopping cart
  • Showing recent transactions
  • Storing unique categories
  • Mapping user IDs to usernames
  • Filtering search results
  • Sorting products by price
  • Grouping expenses by category
  • Displaying API responses in a LazyColumn

Instead of creating separate variables for every item, Kotlin provides collections to organize and process multiple values efficiently.

Kotlin supports three main collection types:

  1. List — An ordered collection of elements.
  2. Set — A collection of unique elements.
  3. Map — A collection of key-value pairs.

Kotlin also provides powerful collection operations such as filter(), map(), find(), sortedBy(), and groupBy().

In this tutorial, we’ll explore Kotlin collections from beginner to intermediate level with practical Android examples.


What You’ll Learn

By the end of this tutorial, you’ll understand:

  • What Kotlin collections are
  • List and MutableList
  • Set and MutableSet
  • Map and MutableMap
  • Read-only vs mutable collections
  • Iterating through collections
  • Adding and removing elements
  • filter() and map()
  • forEach() and forEachIndexed()
  • find() and firstOrNull()
  • any(), all(), and none()
  • sorted(), sortedBy(), and sortedDescending()
  • groupBy() and associateBy()
  • distinct() and distinctBy()
  • sumOf(), count(), and average()
  • Null handling in collections
  • Practical Android use cases
  • Jetpack Compose LazyColumn integration

Let’s begin!


1. What Are Collections in Kotlin?

A collection is a structure used to store and manage multiple values.

Consider an Android application that displays five usernames.

Without collections:

val user1 = "Alex"
val user2 = "Emma"
val user3 = "John"
val user4 = "Sophia"
val user5 = "David"

Managing these variables individually becomes difficult as the number of users increases.

Instead, we can use a Kotlin List.

val users = listOf(
    "Alex",
    "Emma",
    "John",
    "Sophia",
    "David"
)

Now all usernames are stored in a single collection.

We can easily iterate, search, filter, and transform the data.

Main Kotlin Collection Types

CollectionDescriptionDuplicates
ListOrdered collectionAllowed
SetCollection of unique elementsNot allowed
MapKey-value pairs with unique keysKeys must be unique

Each collection has different characteristics and use cases.


2. Kotlin List

A List is an ordered collection of elements.

Lists allow duplicate values, and elements can be accessed by index.

Syntax

val items = listOf("A", "B", "C")

Example

fun main() {

    val fruits = listOf(
        "Apple",
        "Banana",
        "Orange",
        "Mango"
    )

    println(fruits)
}

Output:

[Apple, Banana, Orange, Mango]

Important Characteristics

  • Elements maintain their order.
  • Duplicate elements are allowed.
  • Elements can be accessed using indexes.
  • A List exposes read-only operations.

A read-only List does not provide functions such as add() or remove().


3. Accessing List Elements

Kotlin List indexes start from zero.

Example

fun main() {

    val fruits = listOf(
        "Apple",
        "Banana",
        "Orange"
    )

    println(fruits[0])
    println(fruits[1])
    println(fruits[2])
}

Output:

Apple
Banana
Orange

Using first() and last()

val fruits = listOf("Apple", "Banana", "Orange")

println(fruits.first())
println(fruits.last())

Output:

Apple
Orange

Safe Access with getOrNull()

Accessing an invalid index with [] throws an exception.

Use getOrNull() when an index may be outside the collection.

val fruits = listOf("Apple", "Banana")

println(fruits.getOrNull(5))

Output:

null

This is useful when working with dynamically changing lists.


4. Kotlin MutableList

A MutableList allows us to add, remove, and update elements.

Syntax

val items = mutableListOf("A", "B")

Example

fun main() {

    val fruits = mutableListOf(
        "Apple",
        "Banana"
    )

    fruits.add("Orange")

    println(fruits)
}

Output:

[Apple, Banana, Orange]

Updating an Element

val fruits = mutableListOf(
    "Apple",
    "Banana",
    "Orange"
)

fruits[1] = "Mango"

println(fruits)

Output:

[Apple, Mango, Orange]

Removing an Element

fruits.remove("Apple")

println(fruits)

Output:

[Mango, Orange]

Common MutableList Operations

OperationDescription
add()Adds an element
addAll()Adds multiple elements
remove()Removes a matching element
removeAt()Removes by index
clear()Removes all elements
set()Updates an element
contains()Checks whether an element exists

List vs MutableList

Use List when the caller should only read the collection.

Use MutableList when collection modifications are required.

Important: Kotlin’s read-only List interface is not a guarantee of deep immutability. A read-only reference can still point to a collection that another reference modifies.


5. Iterating Through a Kotlin List

We often need to process every element in a collection.

Kotlin provides several iteration techniques.

Using for Loop

val fruits = listOf(
    "Apple",
    "Banana",
    "Orange"
)

for (fruit in fruits) {
    println(fruit)
}

Output:

Apple
Banana
Orange

Using forEach()

fruits.forEach { fruit ->
    println(fruit)
}

Using forEachIndexed()

fruits.forEachIndexed { index, fruit ->
    println("$index: $fruit")
}

Output:

0: Apple
1: Banana
2: Orange

When to Use Each?

Use a for loop for general iteration.

Use forEach() for concise element processing.

Use forEachIndexed() when both the element and its index are needed.


6. Kotlin Set

A Set is a collection of unique elements.

It does not allow duplicate values.

Example

fun main() {

    val numbers = setOf(
        10,
        20,
        30,
        20,
        10
    )

    println(numbers)
}

Output:

[10, 20, 30]

The duplicate values are removed.

When Should You Use a Set?

Sets are useful for:

  • Unique category names
  • Selected item IDs
  • Unique usernames
  • Permission identifiers
  • Removing duplicates
  • Membership checks

Important

The general Set interface does not promise a particular iteration order. Some Kotlin set implementations preserve insertion order, but code should not depend on ordering unless the chosen implementation guarantees it.


7. Kotlin MutableSet

A MutableSet allows us to add and remove unique elements.

Example

fun main() {

    val categories = mutableSetOf(
        "Android",
        "Flutter"
    )

    categories.add("Kotlin")

    categories.add("Android")

    println(categories)
}

The second "Android" value is not added because it already exists.

Removing Elements

categories.remove("Flutter")

Checking Membership

println("Kotlin" in categories)

Output:

true

Practical Example

Suppose a user selects multiple filter categories.

A Set helps prevent duplicate selections.

val selectedCategories = mutableSetOf<String>()

selectedCategories.add("Kotlin")
selectedCategories.add("Android")
selectedCategories.add("Kotlin")

The set contains only two unique category names.


8. Kotlin Map

A Map stores key-value pairs.

Each key must be unique.

Syntax

val map = mapOf(
    key1 to value1,
    key2 to value2
)

Example

fun main() {

    val users = mapOf(
        1 to "Alex",
        2 to "Emma",
        3 to "John"
    )

    println(users)
}

Output:

{1=Alex, 2=Emma, 3=John}

Accessing Values

println(users[1])
println(users[2])

Output:

Alex
Emma

Missing Keys

println(users[10])

Output:

null

Maps are useful when values need to be accessed through unique identifiers.


9. Kotlin MutableMap

A MutableMap allows adding, updating, and removing key-value pairs.

Example

fun main() {

    val scores = mutableMapOf(
        "Alex" to 90,
        "Emma" to 85
    )

    scores["John"] = 95

    scores["Alex"] = 92

    println(scores)
}

Output:

{Alex=92, Emma=85, John=95}

Removing a Key

scores.remove("Emma")

Checking a Key

println(scores.containsKey("Alex"))

Checking a Value

println(scores.containsValue(95))

Iterating Through a Map

scores.forEach { (name, score) ->
    println("$name scored $score")
}

Maps are commonly used for lookups, configuration, and grouped application data.


10. Kotlin filter() Function

The filter() function creates a new collection containing elements that satisfy a condition.

Example

fun main() {

    val numbers = listOf(
        10, 15, 20, 25, 30
    )

    val evenNumbers = numbers.filter {
        it % 2 == 0
    }

    println(evenNumbers)
}

Output:

[10, 20, 30]

Explanation

The condition:

it % 2 == 0

checks whether a number is even.

Only matching elements are included.

Practical Android Example

data class Product(
    val name: String,
    val price: Int
)

val products = listOf(
    Product("Phone", 15000),
    Product("Mouse", 800),
    Product("Keyboard", 2500)
)

val affordableProducts = products.filter {
    it.price < 5000
}

This produces a list containing Mouse and Keyboard.

Filtering is useful for product searches, transaction history, and category selection.


11. Kotlin map() Function

The map() function transforms each element into a new value.

Example

fun main() {

    val numbers = listOf(1, 2, 3, 4)

    val squares = numbers.map {
        it * it
    }

    println(squares)
}

Output:

[1, 4, 9, 16]

Practical Example

val usernames = listOf(
    "alex",
    "emma",
    "john"
)

val uppercaseNames = usernames.map {
    it.uppercase()
}

println(uppercaseNames)

Output:

[ALEX, EMMA, JOHN]

Difference Between filter() and map()

FunctionPurpose
filter()Select matching elements
map()Transform elements

You can combine both operations.


12. Combining filter() and map()

Example

data class Product(
    val name: String,
    val price: Int
)

fun main() {

    val products = listOf(
        Product("Phone", 15000),
        Product("Mouse", 800),
        Product("Keyboard", 2500)
    )

    val names = products
        .filter { it.price < 5000 }
        .map { it.name }

    println(names)
}

Output:

[Mouse, Keyboard]

How It Works

First:

filter { it.price < 5000 }

selects affordable products.

Then:

map { it.name }

extracts their names.

This pattern is commonly used when preparing data for Android UI components.


13. Kotlin find() and firstOrNull()

Sometimes we need to find a single matching element.

Using find()

val numbers = listOf(5, 10, 15, 20)

val result = numbers.find {
    it > 12
}

println(result)

Output:

15

Using firstOrNull()

val result = numbers.firstOrNull {
    it > 100
}

println(result)

Output:

null

Why Use firstOrNull()?

Unlike first(), which throws an exception when no element matches, firstOrNull() returns null.

This is useful when working with optional search results.


14. Kotlin any(), all(), and none()

These functions check whether collection elements satisfy a condition.

any()

Returns true if at least one element matches.

val numbers = listOf(5, 10, 15)

println(numbers.any { it > 12 })

Output:

true

all()

Returns true if every element matches.

println(numbers.all { it > 0 })

Output:

true

none()

Returns true if no elements match.

println(numbers.none { it < 0 })

Output:

true

Practical Uses

These functions are useful for:

  • Form validation
  • Checking selected items
  • Detecting incomplete tasks
  • Verifying product availability
  • Checking collection conditions

15. Sorting Kotlin Collections

Kotlin provides several sorting functions.

sorted()

val numbers = listOf(30, 10, 40, 20)

println(numbers.sorted())

Output:

[10, 20, 30, 40]

sortedDescending()

println(numbers.sortedDescending())

Output:

[40, 30, 20, 10]

sortedBy()

Sort objects by a property.

data class Product(
    val name: String,
    val price: Int
)

val products = listOf(
    Product("Phone", 15000),
    Product("Mouse", 800),
    Product("Keyboard", 2500)
)

val sortedProducts = products.sortedBy {
    it.price
}

The resulting order is:

Mouse
Keyboard
Phone

sortedByDescending()

val expensiveFirst = products.sortedByDescending {
    it.price
}

Sorting is useful for product listings, leaderboards, and transaction histories.


16. Kotlin distinct() and distinctBy()

The distinct() function removes duplicate values.

Example

val numbers = listOf(
    1, 2, 2, 3, 3, 4
)

println(numbers.distinct())

Output:

[1, 2, 3, 4]

distinctBy()

Use distinctBy() when uniqueness depends on a specific property.

data class User(
    val id: Int,
    val name: String
)

val users = listOf(
    User(1, "Alex"),
    User(2, "Emma"),
    User(1, "Alex Updated")
)

val uniqueUsers = users.distinctBy {
    it.id
}

The first user with each unique ID is retained.

This can help remove duplicate entries from imported or merged data.


17. Kotlin groupBy()

The groupBy() function organizes elements into groups based on a key.

Example

data class Expense(
    val title: String,
    val category: String,
    val amount: Int
)

fun main() {

    val expenses = listOf(
        Expense("Lunch", "Food", 200),
        Expense("Bus", "Travel", 50),
        Expense("Dinner", "Food", 300),
        Expense("Taxi", "Travel", 250)
    )

    val groupedExpenses = expenses.groupBy {
        it.category
    }

    groupedExpenses.forEach { (category, items) ->

        println("$category:")

        items.forEach { expense ->
            println("${expense.title}: ₹${expense.amount}")
        }
    }
}

Output:

Food:
Lunch: ₹200
Dinner: ₹300
Travel:
Bus: ₹50
Taxi: ₹250

Practical Android Uses

Grouping is useful for:

  • Expenses by category
  • Transactions by date
  • Products by category
  • Contacts by initial letter
  • Notifications by type

18. Kotlin associateBy()

The associateBy() function converts a collection into a Map using a selected key.

Example

data class User(
    val id: Int,
    val name: String
)

fun main() {

    val users = listOf(
        User(1, "Alex"),
        User(2, "Emma"),
        User(3, "John")
    )

    val usersById = users.associateBy {
        it.id
    }

    println(usersById[2])
}

Output:

User(id=2, name=Emma)

Important

If multiple elements produce the same key, later elements replace earlier values in the resulting Map.

Use groupBy() instead when you need to preserve multiple values under the same key.


19. Kotlin Collection Aggregation Functions

Kotlin provides functions for calculating values across collections.

count()

val numbers = listOf(10, 20, 30)

println(numbers.count())

Output:

3

sum()

println(numbers.sum())

Output:

60

average()

println(numbers.average())

Output:

20.0

sumOf()

Use sumOf() to calculate totals from object properties.

data class Expense(
    val title: String,
    val amount: Int
)

val expenses = listOf(
    Expense("Food", 200),
    Expense("Travel", 150),
    Expense("Shopping", 500)
)

val total = expenses.sumOf {
    it.amount
}

println(total)

Output:

850

These functions are useful for reports, dashboards, and analytics screens.


20. Handling Nullable Elements in Collections

Kotlin collections can contain nullable values.

Example

val names: List<String?> = listOf(
    "Alex",
    null,
    "Emma",
    null,
    "John"
)

filterNotNull()

val validNames = names.filterNotNull()

println(validNames)

Output:

[Alex, Emma, John]

mapNotNull()

Use mapNotNull() when a transformation may return null.

val values = listOf(
    "10",
    "20",
    "invalid",
    "40"
)

val numbers = values.mapNotNull {
    it.toIntOrNull()
}

println(numbers)

Output:

[10, 20, 40]

This is useful when converting user input or processing partially valid external data.


21. Practical Android Example: Product Search and Sorting

Let’s create a small product catalog.

Step 1: Product Model

data class Product(
    val id: Int,
    val name: String,
    val category: String,
    val price: Int
)

Step 2: Sample Products

val products = listOf(
    Product(1, "Android Phone", "Electronics", 15000),
    Product(2, "Bluetooth Mouse", "Accessories", 800),
    Product(3, "Keyboard", "Accessories", 2500),
    Product(4, "Tablet", "Electronics", 12000),
    Product(5, "USB Cable", "Accessories", 300)
)

Step 3: Search Products

fun searchProducts(
    products: List<Product>,
    query: String
): List<Product> {

    return products.filter {
        it.name.contains(
            query,
            ignoreCase = true
        )
    }
}

Step 4: Sort Products

fun sortProductsByPrice(
    products: List<Product>
): List<Product> {

    return products.sortedBy {
        it.price
    }
}

Step 5: Filter by Category

fun filterByCategory(
    products: List<Product>,
    category: String
): List<Product> {

    return products.filter {
        it.category == category
    }
}

Usage

fun main() {

    val searchResults = searchProducts(
        products,
        "phone"
    )

    println(searchResults)

    val sortedProducts = sortProductsByPrice(products)

    println(sortedProducts.map { it.name })

    val accessories = filterByCategory(
        products,
        "Accessories"
    )

    println(accessories.map { it.name })
}

Benefits

This example demonstrates how collections simplify:

  • Search functionality
  • Category filtering
  • Price sorting
  • Product list transformations

These operations are common in e-commerce, finance, media, and utility applications.


22. Jetpack Compose Mini-Project: Searchable Product List

Let’s build a simple Android product list using Kotlin collections and Jetpack Compose.

Our application will support:

  • Displaying products
  • Searching by product name
  • Filtering products
  • Sorting by price
  • Displaying results in LazyColumn

Step 1: Create the Product Model

data class ShopProduct(
    val id: Int,
    val name: String,
    val category: String,
    val price: Int
)

Step 2: Create the Product List

fun getSampleProducts(): List<ShopProduct> {

    return listOf(
        ShopProduct(1, "Android Phone", "Electronics", 15000),
        ShopProduct(2, "Bluetooth Mouse", "Accessories", 800),
        ShopProduct(3, "Wireless Keyboard", "Accessories", 2500),
        ShopProduct(4, "Android Tablet", "Electronics", 12000),
        ShopProduct(5, "USB Cable", "Accessories", 300),
        ShopProduct(6, "Smart Watch", "Wearables", 4500)
    )
}

Step 3: Create the Jetpack Compose Screen

@Composable
fun ProductListScreen() {

    val products = remember {
        getSampleProducts()
    }

    var searchQuery by rememberSaveable {
        mutableStateOf("")
    }

    var sortAscending by rememberSaveable {
        mutableStateOf(true)
    }

    val filteredProducts = remember(
        products,
        searchQuery,
        sortAscending
    ) {
        products
            .filter { product ->
                product.name.contains(
                    searchQuery,
                    ignoreCase = true
                )
            }
            .let { result ->
                if (sortAscending) {
                    result.sortedBy { it.price }
                } else {
                    result.sortedByDescending { it.price }
                }
            }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {

        Text(
            text = "Product Explorer",
            style = MaterialTheme.typography.headlineMedium
        )

        OutlinedTextField(
            value = searchQuery,
            onValueChange = {
                searchQuery = it
            },
            modifier = Modifier.fillMaxWidth(),
            label = {
                Text("Search Products")
            },
            singleLine = true
        )

        Button(
            onClick = {
                sortAscending = !sortAscending
            }
        ) {

            Text(
                if (sortAscending) {
                    "Price: Low to High"
                } else {
                    "Price: High to Low"
                }
            )
        }

        Text(
            text = "${filteredProducts.size} Products Found",
            style = MaterialTheme.typography.titleMedium
        )

        LazyColumn(
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {

            items(
                items = filteredProducts,
                key = { product -> product.id }
            ) { product ->

                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {

                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(6.dp)
                    ) {

                        Text(
                            text = product.name,
                            style = MaterialTheme.typography.titleMedium
                        )

                        Text(
                            text = product.category,
                            style = MaterialTheme.typography.bodyMedium
                        )

                        Text(
                            text = "₹${product.price}",
                            color = MaterialTheme.colorScheme.primary,
                            style = MaterialTheme.typography.titleSmall
                        )
                    }
                }
            }
        }
    }
}

Required Imports

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

Expected UI

+--------------------------------+
|                                |
|       Product Explorer         |
|                                |
| +----------------------------+ |
| | Search Products            | |
| +----------------------------+ |
|                                |
| [ Price: Low to High ]         |
|                                |
| 6 Products Found               |
|                                |
| +----------------------------+ |
| | USB Cable                  | |
| | Accessories                | |
| | ₹300                       | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| | Bluetooth Mouse            | |
| | Accessories                | |
| | ₹800                       | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| | Wireless Keyboard          | |
| | Accessories                | |
| | ₹2500                      | |
| +----------------------------+ |
|                                |
| +----------------------------+ |
| | Smart Watch                | |
| | Wearables                  | |
| | ₹4500                      | |
| +----------------------------+ |
|                                |
+--------------------------------+

The remaining products appear when the user scrolls.

How It Works

We created a product list using:

listOf()

We filter products using:

filter()

We sort products using:

sortedBy()
sortedByDescending()

The search query and sort direction are stored in Compose state.

When either value changes, the filtered list is recalculated.

LazyColumn efficiently displays the resulting products.

Why Use LazyColumn?

Unlike a regular Column that composes all its children immediately, LazyColumn composes and lays out items as needed.

This makes it suitable for larger, scrollable lists.

Important Production Note

For very large datasets, consider using:

  • ViewModel for state management
  • StateFlow for reactive updates
  • Room for local data
  • Paging for large datasets
  • Debouncing for expensive search operations

We’ll explore these technologies in future tutorials.


23. Kotlin Collections Performance Tips

Collections are convenient, but developers should understand their performance characteristics.

Avoid Unnecessary Transformations

For example:

val result = products
    .filter { it.price > 1000 }
    .map { it.name }

This is readable and appropriate for many applications.

However, multiple operations on standard collections can create intermediate collections.

Consider Sequences for Complex Pipelines

val result = products
    .asSequence()
    .filter { it.price > 1000 }
    .map { it.name }
    .toList()

Sequences process elements lazily.

They can be useful for large collections or multi-step transformations.

However, sequences are not automatically faster for every situation.

For small collections, standard collection operations may be simpler and more efficient.

Use Appropriate Collection Types

  • List for ordered elements
  • Set for unique elements
  • Map for key-based lookups

Avoid Blocking the Main Thread

Large collection transformations can consume significant CPU time.

In Android applications, expensive processing should be performed away from the main thread when appropriate.


24. Common Kotlin Collections Mistakes

Mistake 1: Modifying a Read-Only List

Incorrect:

val users = listOf("Alex", "Emma")

users.add("John")

Correct:

val users = mutableListOf("Alex", "Emma")

users.add("John")

Mistake 2: Accessing an Invalid Index

Unsafe:

val users = listOf("Alex")

println(users[5])

Safer:

println(users.getOrNull(5))

Mistake 3: Assuming Set Allows Duplicates

val numbers = setOf(1, 1, 2, 3)

The resulting set contains only unique elements.

Mistake 4: Assuming Map Allows Duplicate Keys

val users = mapOf(
    1 to "Alex",
    1 to "Emma"
)

The later value replaces the earlier value for the same key.

Mistake 5: Mutating a Regular MutableList Without Observable Compose State

In Jetpack Compose, changing an ordinary mutable collection does not automatically notify Compose.

For example:

val items = remember {
    mutableListOf("Apple")
}

Calling items.add() does not by itself trigger recomposition.

Prefer observable immutable-list updates:

var items by remember {
    mutableStateOf(listOf("Apple"))
}

items = items + "Banana"

Or use an appropriate Compose snapshot state collection such as mutableStateListOf().

Mistake 6: Using first() on an Empty List

Unsafe:

emptyList<String>().first()

Safer:

emptyList<String>().firstOrNull()

25. Kotlin Collections Quick Reference

OperationExamplePurpose
Create ListlistOf(1, 2, 3)Read-only ordered collection
Mutable ListmutableListOf(1, 2)Modifiable list
SetsetOf(1, 2, 2)Unique values
Mutable SetmutableSetOf(1, 2)Modifiable set
MapmapOf(1 to "Alex")Key-value pairs
Mutable MapmutableMapOf(1 to "Alex")Modifiable map
Filterfilter { it > 10 }Select matching values
Mapmap { it * 2 }Transform values
Findfind { it > 10 }First match or null
Sortsorted()Ascending order
GroupgroupBy { it.category }Group elements
Distinctdistinct()Remove duplicates
SumsumOf { it.amount }Calculate total
Null removalfilterNotNull()Remove null values
Indexed loopforEachIndexed()Access index and value

26. Practical Exercises

Try these exercises to improve your Kotlin collections skills.

Exercise 1: Student List

Create a list of five student names.

Print each name using forEach().

Exercise 2: Mutable Shopping Cart

Create a MutableList of products.

Add two products and remove one.

Display the final list.

Exercise 3: Unique Categories

Create a Set containing duplicate category names.

Display only unique categories.

Exercise 4: User Map

Create a Map where the key is a user ID and the value is a username.

Retrieve a username using its ID.

Exercise 5: Filter Products

Create a list of products.

Filter products costing less than ₹5,000.

Exercise 6: Sort Expenses

Create a list of expenses.

Sort them by amount in descending order.

Exercise 7: Group Transactions

Create a list of transactions.

Group them by category using groupBy().

Exercise 8: Jetpack Compose Mini-Project

Build a searchable product list using:

  • Data classes
  • List
  • filter()
  • sortedBy()
  • LazyColumn
  • OutlinedTextField
  • Compose state

What We’ve Learned

In this tutorial, we learned:

  • Kotlin collections
  • List and MutableList
  • Set and MutableSet
  • Map and MutableMap
  • Collection iteration
  • Adding and removing elements
  • Filtering collections
  • Transforming collections
  • Searching collections
  • Sorting collections
  • Removing duplicates
  • Grouping data
  • Creating lookup Maps
  • Aggregation functions
  • Handling nullable elements
  • Collection performance considerations
  • Jetpack Compose LazyColumn integration
  • Common collection mistakes
  • Kotlin collections best practices

Kotlin collections are essential for managing and processing data in Android applications.

Whether you’re displaying products, filtering transactions, organizing user information, or building reactive Jetpack Compose screens, collections provide powerful and expressive tools.


What’s Next?

In our next tutorial, we’ll explore:

Kotlin Lambdas and Higher-Order Functions Explained with Examples

You’ll learn:

  • What lambda expressions are
  • Lambda syntax
  • Function types
  • Passing functions as parameters
  • Higher-order functions
  • Returning functions
  • Trailing lambda syntax
  • The it keyword
  • Function references
  • Inline functions
  • Practical Android examples
  • Lambdas in Jetpack Compose button callbacks

Happy Coding!

Continue learning modern Android development with Moiks Developer Blog.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment