Home > Enterprise >  Sorted map with custom comparator
Sorted map with custom comparator

Time:07-23

I want to create a sorted map with a composite key. If it didn't need to be sorted, I would use

val myMap = mapOf(
    Pair(1,"a") to "A",
    Pair(2,"a") to "AA",
    Pair(1,"b") to "B"
)

But it has to be a sorted map and this doesn't work:

val myMap = sortedMapOf(
    Pair(1,"a") to "A",
    Pair(2,"a") to "AA",
    Pair(1,"b") to "B"
)

What's the most idiomatic way to create a sorted map with a custom comparator? I want it to compare by the first element of the pair and then by the second.

CodePudding user response:

sortedMapOf has an overload that takes a comparator as its first argument.

val myMap = sortedMapOf(
  compareBy<Pair<Int, String>> { it.first } then compareBy { it.second },
  Pair(1,"a") to "A",
  Pair(2,"a") to "AA",
  Pair(1,"b") to "B",
)
  • Related