0Pricing
Kotlin Academy · Lesson

Data Classes in Collections and as Map Keys

Use data classes in sets and maps leveraging structural equality.

Data Classes in Collections and as Map Keys is a free Kotlin Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Data Classes as Value Objects

Because data classes override equals and hashCode structurally, they work perfectly in sets and as map keys — unlike regular classes.

Regular Class: Bad Map Key

A regular class uses reference equality by default. Two equal-looking objects are different map keys.
class Key(val id: Int)  // no equals/hashCode
val map = mutableMapOf<Key, String>()
val k1 = Key(1)
val k2 = Key(1)  // same id, different object
map[k1] = "value"
println(map[k2])  // null! k2 != k1 by reference

Data Class: Correct Map Key

A data class uses structural equality. Two objects with the same properties are equal.
data class Key(val id: Int)
val map = mutableMapOf<Key, String>()
val k1 = Key(1)
val k2 = Key(1)
map[k1] = "value"
println(map[k2])  // "value"! Equal by value

Data Class in a Set

Sets use equals and hashCode to deduplicate. Data classes deduplicate correctly.
data class Tag(val name: String)
val tags = mutableSetOf<Tag>()
tags.add(Tag("kotlin"))
tags.add(Tag("kotlin"))  // duplicate
tags.add(Tag("java"))
println(tags.size)  // 2 (not 3)

GroupBy with Data Classes

Group collections by a data class key.
data class Category(val name: String, val parent: String)
val items = listOf(
    "List" to Category("Collections", "stdlib"),
    "Map" to Category("Collections", "stdlib"),
    "Flow" to Category("Coroutines", "kotlinx")
)
val grouped = items.groupBy { it.second }
println(grouped.keys.size)  // 2

Counting Occurrences with Map

Count occurrences of structured data using a data class as map key.
data class Pair2(val x: Int, val y: Int)
val points = listOf(Pair2(1,2), Pair2(1,2), Pair2(3,4))
val counts = points.groupingBy { it }.eachCount()
println(counts)  // {Pair2(x=1, y=2)=2, Pair2(x=3, y=4)=1}

Nested Data Classes

Data classes can contain other data classes. Equals and hashCode are deep for nested data classes.
data class Address(val city: String, val country: String)
data class Person(val name: String, val address: Address)
val p1 = Person("Alice", Address("Berlin", "DE"))
val p2 = Person("Alice", Address("Berlin", "DE"))
println(p1 == p2)  // true

sortedBy with Data Classes

Sort a list of data class instances by a property.
data class Student(val name: String, val grade: Double)
val students = listOf(
    Student("Bob", 3.2),
    Student("Alice", 3.8),
    Student("Charlie", 2.9)
)
println(students.sortedBy { it.grade })

Data Classes and Caching

Use data classes as cache keys in a HashMap when the cache key is composite.
data class CacheKey(val userId: Long, val resourceType: String)
val cache = HashMap<CacheKey, ByteArray>()
val key = CacheKey(42, "avatar")
cache[key] = byteArrayOf(1, 2, 3)
println(cache[CacheKey(42, "avatar")] != null)  // true

distinct on Data Classes

distinct() on a list of data classes uses their equals to remove duplicates.
data class Event(val type: String, val ts: Long)
val events = listOf(
    Event("click", 1000),
    Event("click", 1000),  // duplicate
    Event("scroll", 2000)
)
println(events.distinct().size)  // 2

Immutable Keys Are Safer

Always use data classes with val properties as map/set keys. Mutating a key after insertion breaks the data structure.
data class ImmutableKey(val id: Int)  // val properties only
// DON'T: data class MutableKey(var id: Int)  // changing id breaks map!

Quick Check

Why do data classes work correctly as Map keys while regular classes often don't?

Recap

Data classes work as Map keys and Set elements because they have correct structural equals/hashCode. Use val properties to keep keys immutable. Leverage groupBy, distinct, and sortedBy with data classes for powerful queries.

Frequently asked questions

Is the “Data Classes in Collections and as Map Keys” lesson free?

Yes — the full text of “Data Classes in Collections and as Map Keys” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Data Classes in Collections and as Map Keys”?

Use data classes in sets and maps leveraging structural equality. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Data Classes in Collections and as Map Keys” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Data Class Basics: Auto-generated Methods
  2. Copying with copy() and Partial Overrides
  3. Destructuring Declarations with componentN
  4. Data Classes in Collections and as Map Keys
← Back to Kotlin Academy