Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorted map with custom comparator

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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",
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading