Lesson 3
Diving into Sorted Maps with Kotlin
Diving into Sorted Maps

Hello again! This lesson's topic is Sorted Maps. Similar to other map structures, Sorted Maps store key-value pairs but in an ordered manner. Learning about Sorted Maps enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Sorted Maps using Kotlin's collection library.

Introduction: Sorted Maps in Kotlin

In Kotlin, sorted maps can be seamlessly created and used, providing a convenient way to store key-value pairs while maintaining order automatically. Unlike unordered maps like HashMap, Kotlin provides the sortedMap feature, which by default arranges its keys in natural order (if they implement Comparable). Alternatively, a custom comparator can be used for specific sorting requirements.

Kotlin natively supports sorted maps through functions like sortedMapOf(), which construct a sorted map with entries placed in ascending order based on keys. This makes data manipulation efficient and organized, similar to a well-ordered library where items are systematically sorted.

Discovering SortedMap in Kotlin

To create a sorted map in Kotlin, you can use the sortedMapOf() function, which allows for easy initialization of key-value pairs. The keys should comply with comparability rules, either being comparable themselves or defined by a custom comparator. Here's an illustration:

Kotlin
1fun main() { 2 // Sorted map with fruits as keys and corresponding counts as values 3 val sortedMap = sortedMapOf("banana" to 3, "apple" to 4, "pear" to 1, "orange" to 2) 4 5 // Print the sorted map 6 println(sortedMap) 7}

The output will be:

1{apple=4, banana=3, orange=2, pear=1}

In this example, the keys are sorted in alphabetical order. "apple" appears first since 'a' comes before 'b', 'o', and 'p' in the alphabet, while "pear" comes last because 'p' ranks highest among the key initials.

Traversing SortedMap Methods

Kotlin's sorted maps offer various methods to manage and retrieve data effectively. Here are some essential functions:

  • sortedMap.ceilingKey(key): Use the keys.firstOrNull with a filter to find the smallest key greater than or equal to the given key.
  • sortedMap.floorKey(key): Utilize keys.lastOrNull filtered to identify the largest key less than or equal to the provided key.
  • sortedMap.remove(key): The remove() method removes the specified key entry and returns its associated value.
  • sortedMap[key]: This retrieves the value associated with a given key or returns null if the key is absent.
  • sortedMap.entries.last(): Retrieves the entry with the greatest key or null if the map is empty.
  • sortedMap.maxByOrNull(selector): This returns the entry with the maximum value determined by the given selector function, or null if the map is empty.

Here's how you can implement these methods in Kotlin:

Kotlin
1fun main() { 2 // Initialize sorted map 3 val sortedMap = sortedMapOf("banana" to 3, "apple" to 4, "pear" to 1, "orange" to 2) 4 5 // Ceiling key example 6 println("Ceiling key of 'apple': ${sortedMap.keys.firstOrNull { it >= "apple" }}") // Output: apple 7 8 // Floor key example 9 println("Floor key of 'apple': ${sortedMap.keys.lastOrNull { it <= "apple" }}") // Output: apple 10 11 // Remove 'apple' and print the removed value 12 val removedValue = sortedMap.remove("apple") 13 println("Removed value: $removedValue") // Output: 4 14 15 // Attempt to fetch a nonexisting key 16 val value = sortedMap["apple"] 17 if (value == null) { 18 println("Value: Not found") // Output: Value: Not found 19 } 20 21 // Get the last key-value pair 22 println("Last entry: ${sortedMap.entries.lastOrNull()}") // Output: pear=1 23 24 // Max by value example 25 val maxEntry = sortedMap.maxByOrNull { it.value } 26 println("Entry with max value: $maxEntry") // Output: orange=2 27}
Lesson Summary

Congratulations! You have successfully delved into Sorted Maps using Kotlin. This exploration covered the use of sortedMapOf() to create sorted map instances and navigate through Kotlin's available methods for sorting and manipulating data. Next, you can look forward to hands-on exercises to solidify your understanding and expand your skill set. Keep practicing!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.