Skip to main content
Kotlin Basics
CHAPTER 21 Beginner

Collections Framework in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 21

Collections Framework in Kotlin

1. Chapter Introduction

In Chapter 10, we learned how to create Lists, Sets, and Maps. In Chapter 19, we learned how to filter them using Lambdas. Now, we will combine this knowledge and explore the massive power of the Kotlin Collections Framework. Kotlin provides dozens of built-in extension functions to sort, search, group, and transform collections. Mastering these will replace hundreds of lines of complex for loop logic.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Sort collections (Ascending, Descending, By specific properties).
  • Group collections into Maps.
  • Check conditions using any, all, and none.
  • Find specific elements safely.
  • Build a Mini Project: Inventory Manager.

3. Sorting Collections

Kotlin makes sorting incredibly easy.
  • sorted(): Sorts numbers or strings in natural ascending order.
  • sortedDescending(): Sorts in descending order.
kotlin
123456
fun main() {
    val numbers = listOf(5, 2, 8, 1)
    
    println(numbers.sorted())           // [1, 2, 5, 8]
    println(numbers.sortedDescending()) // [8, 5, 2, 1]
}

If you have a list of Objects (like Product data classes), you must tell Kotlin *which property* to sort by using sortedBy.

kotlin
123456789101112131415
data class Product(val name: String, val price: Double)

fun main() {
    val cart = listOf(
        Product("Laptop", 1200.0),
        Product("Mouse", 25.0),
        Product("Keyboard", 75.0)
    )

    // Sort by price! (Using trailing lambda)
    val sortedCart = cart.sortedBy { it.price }
    
    println(sortedCart) 
    // Output: [Product(name=Mouse, price=25.0), Product(name=Keyboard, price=75.0), Product(name=Laptop, price=1200.0)]
}

4. Grouping Data (groupBy)

groupBy takes a List and converts it into a Map, grouping items by a specific key. This is immensely powerful for analytics.
kotlin
123456789101112131415
data class Person(val name: String, val city: String)

fun main() {
    val people = listOf(
        Person("Alice", "New York"),
        Person("Bob", "London"),
        Person("Charlie", "New York")
    )

    // Group the list into a Map where the Key is the City!
    val groupedByCity = people.groupBy { it.city }

    // Result is a Map<String, List<Person>>
    println(groupedByCity["New York"]) // Prints Alice and Charlie
}

5. Checking Conditions (any, all, none)

Often you just need a Boolean answer about a collection.
  • any: Is there at least one item that matches?
  • all: Do ALL items match?
  • none: Do ZERO items match?
kotlin
12345
val numbers = listOf(1, 2, 3, 4, 5)

println(numbers.any { it > 4 })  // true (5 is greater than 4)
println(numbers.all { it > 0 })  // true (all are greater than 0)
println(numbers.none { it < 0 }) // true (none are less than 0)

6. Finding Elements Safely

Instead of writing a for loop to search for an item, use find. find returns the FIRST item matching the condition, or null if it doesn't exist.
kotlin
1234567
val words = listOf("Apple", "Banana", "Cherry")

// Returns "Banana"
val result = words.find { it.startsWith("B") } 

// Returns null
val missing = words.find { it.startsWith("Z") } 

7. Mini Project: Inventory Manager

Let's manage a store inventory using advanced collection functions.
kotlin
12345678910111213141516171819202122232425
data class Item(val name: String, val category: String, val price: Double, val inStock: Boolean)

fun main() {
    val inventory = listOf(
        Item("Laptop", "Electronics", 999.0, true),
        Item("Phone", "Electronics", 500.0, false),
        Item("Desk", "Furniture", 150.0, true),
        Item("Chair", "Furniture", 50.0, true)
    )

    // 1. Check if ANY item is out of stock
    val hasOutofStock = inventory.any { !it.inStock }
    println("Any out of stock? $hasOutofStock")

    // 2. Get only Electronics that are In Stock, sorted by price
    val availableElectronics = inventory
        .filter { it.category == "Electronics" && it.inStock }
        .sortedBy { it.price }
        
    println("Available Electronics: $availableElectronics")

    // 3. Group by Category
    val catalog = inventory.groupBy { it.category }
    println("Total Categories: ${catalog.keys.size}")
}

8. Common Mistakes

  • Using Mutable Lists needlessly: It is tempting to write val sortedList = mutableListOf() and use a for loop to sort items manually. This is "Java thinking". Trust the functional operators! Let .sortedBy create the new immutable list for you.

9. Best Practices

  • Chain operations logically: When chaining filter and map, always filter first. It reduces the size of the list, so map has to do less work.

10. Exercises

  1. 1. Create a list of integers: 10, 5, 20, 15.
  1. 2. Use .sortedDescending() to order them highest to lowest.
  1. 3. Use .find { } to search for a number greater than 15. Print the result.

11. MCQs with Answers

Question 1

Which function sorts a list of numbers from lowest to highest?

Question 2

If you have a list of Objects, how do you sort them by a specific property?

Question 3

Which function returns true if at least ONE item in the list satisfies the condition?

Question 4

Which function returns true ONLY if EVERY item in the list satisfies the condition?

Question 5

What does the .groupBy { } function return?

Question 6

What happens if .find { } cannot locate an item matching the condition?

Q7. Is list.sorted() an operation that alters the original list, or does it return a new list? a) Alters original b) Returns a new list Answer: b) Returns a new list.
Question 8

If you want to check if a list has NO negative numbers, which is the cleanest function to use?

Question 9

If you chain .filter { }.sortedBy { }, which operation runs first?

Question 10

Why are these collection functions referred to as "Higher-Order Functions"?

12. Interview Questions

  • Q: Explain the difference between .map { } and .filter { }. (Answer: Map transforms every element, creating a new list of the same size. Filter evaluates a condition, keeping only items that return true, creating a smaller list).
  • Q: How would you group a list of Employee objects by their department using Kotlin Collections?

13. Summary

The Kotlin Collections Framework provides a staggering amount of utility right out of the box. Functions like groupBy, sortedBy, and find eliminate the massive, nested for loops required in older languages. By embracing these functional paradigms, your code becomes declarative—you tell the compiler *what* you want, rather than explicitly coding *how* to do it.

14. Next Chapter Recommendation

Our data disappears when the application closes. To make data persistent, we must write it to the hard drive. In Chapter 22: File Handling in Kotlin, we will learn how to read and write text files seamlessly.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·