Home > Enterprise >  How to filter and sort dictionary (Map) in Kotlin
How to filter and sort dictionary (Map) in Kotlin

Time:06-28

I am trying to filter and sort dictionary (map) in Kotlin: by key = shouldShow. Is shouldShow = true, sort these objects by key = displayOrder in descending order and get string list with state names. Is it possible to do it and how? Because I am trying and nothing works. Thanks in advance.

Map: [{shouldShow=true, displayOrder=2, state=Alaska}, {shouldShow=false, displayOrder=3, state=Texas}, {shouldShow=true, displayOrder=1, state=Arizona}]

CodePudding user response:

val list = listOf(
  mapOf("shouldShow" to true, "displayOrder" to 2, "state" to "Alaska"),
  mapOf("shouldShow" to false, "displayOrder" to 3, "state" to "Texas"),
  mapOf("shouldShow" to true, "displayOrder" to 1, "state" to "Arizona")
)

val stateNames = list
  .filter { it["shouldShow"] == true }
  .sortedByDescending { it["displayOrder"] as Int }
  .map { it["state"] as String }

println(stateNames)   // [Alaska, Arizona]
  • Related