在不丢失键的情况下按值对 LinkedHashMap<String, Json> 进行排序

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

我将此改装响应主体作为 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"
}
}

我需要按 'noteCurrentTime' 值排序。到目前为止,这就是获取排序值数组的方法。

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)
    }

但是,这仅 returns 排序值,没有键,现在顺序错误。有没有办法对 LinkedHashMap 的值进行排序并保持键的正确顺序?我们将不胜感激。

您可以将地图转换为(键值对的)列表,对其进行排序,然后再将其转换回来。

我真的不知道在您的示例地图值类型中 Json 是什么类型。但是你会在 sortedBy lambda 中转换它,但是这是获得长日期所必需的。

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