Topic Overview

Welcome to our exploration of sorted maps using custom classes and comparators in Kotlin. In today's lesson, we'll learn how to use custom data classes as keys in sorted maps. This approach enhances data organization and access. With the addition of comparators, we can dictate the order in such maps.

Quick Recap on Sorted Maps

A sorted map is a collection with its keys always in order. This arrangement makes operations like searching for keys within a range more efficient. In Kotlin, we often use the sortedMapOf function or TreeMap from Java's standard library for sorted maps:

import java.util.TreeMap

fun main() {
    val sMap = sortedMapOf("a" to 1, "b" to 2, "c" to 3)

    println(sMap)  // Outputs {a=1, b=2, c=3}
}
Introduction to Custom Classes in Kotlin

Custom classes enable us to create objects that fit our data — for instance, a Person data class for employee information or a Book data class for a library database. In Kotlin, data classes provide a concise and idiomatic approach to creating such objects.

Consider this simple data class, for example:

data class Person(val name: String, val age: Int)

fun main() {
    val person = Person(name = "John Doe", age = 30)
    println(person.name)  // Outputs "John Doe"
    println(person.age)   // Outputs 30
}
Using Custom Classes as Keys in Sorted Maps

Using custom classes as map keys helps organize complex multivariate keys in a sorted map. Consider the following example using the Person data class as a key in a sorted map. However, this will not work yet without a comparator.

import java.util.TreeMap

data class Person(val name: String, val age: Int)

fun main() {
    val people = TreeMap<Person, String>()

    val john = Person("John", 30)
    val alice = Person("Alice", 25)

    people[john] = "Programmer"
    people[alice] = "Designer"
}

In this code, John is assigned the value "Programmer", and Alice is assigned the value "Designer." However, this code will produce an error because TreeMap requires a way to compare the Person objects to maintain its order.

Comparators and Their Role in Sorted Maps
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal