简体   繁体   中英

Sort LinkedHashMap<String, Json> by value without losing keys

I have this retrofit response body as LinkedHashMap< String, Json>

"-M74DWOrW0w07BpfmBVo": {
  "noteContent": "Note 1 content",
  "noteCurrentTime": 1589225588206,
  "noteTitle": "Note 1"
},
"-M74Dc2dDAZgVk6q86Rs": {
  "noteContent": "Note 2 content",
  "noteCurrentTime": 1589225990674,
  "noteTitle": "Note 2"
},
"-M74DmbSNQnjEU0Hw4yQ": {
  "noteContent": "Note 3 content",
  "noteCurrentTime": 1589225658614,
  "noteTitle": "Note 3"
}
}

I need to sort by 'noteCurrentTime' value. So far, this is how get the array of sorted values.

private fun sortJsonArray(valuesArray: JSONArray): JSONArray? {
        val sortedValues: MutableList<JSONObject> = ArrayList()
        for (i in 0 until valuesArray.length()) {
            sortedValues.add(valuesArray.getJSONObject(i))
        }
        sortedValues.sortWith(Comparator { lhs, rhs ->
            val lid: Long = lhs.getLong("noteCurrentTime")
            val rid: Long = rhs.getLong("noteCurrentTime")
            lid.compareTo(rid)
        })

        return JSONArray(sortedValues)
    }

However, this only returns sorted values, without keys, which are now in a wrong order. Is there a way to sort values of LinkedHashMap and keep the correct order of keys? Any and all help would be appreciated.

You can convert the map to a list (of key-value pairs), sort that, and then convert it back.

I don't really know what type is Json in your example Map value type. But you would convert it in the sortedBy lambda however is necessary to get your Long date.

val response:  LinkedHashMap<String, Json> = //...
val sorted: Map<String, Json> = response.toList().sortBy { (_, jsonValue) ->
    jsonValue.getLong("noteCurrentTime")
}.toMap()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM