import java.util.*
object TreeMapExample {
@JvmStatic
fun main(args: Array) {
// Creating a TreeMap
val numbers = TreeMap<Int, String>()
// Adding entries
numbers[3] = "Three"
numbers[1] = "One"
numbers[4] = "Four"
numbers[2] = "Two"
// Retrieving a value
val value = numbers[3]
println("Value associated with key 3: $value")
// Iterating over entries
output
Value associated with key 3: Three
Iterating over entries:
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four
Value associated with key 'THREE': Third
First entry: 1=One
Last entry: 4=Four
println("Iterating over entries:")
for ((key, value1) in numbers) {
println("Key: $key, Value: $value1")
}
// Using a custom comparator
val strings = TreeMap<String, String>(java.lang.String.CASE_INSENSITIVE_ORDER)
strings["one"] = "First"
strings["two"] = "Second"
strings["Three"] = "Third"
println("Value associated with key 'THREE': " + strings["THREE"])
// First and last entries
println("First entry: " + numbers.firstEntry())
println("Last entry: " + numbers.lastEntry())
}
}