按值对 LinkedHashMap<String, Json> 进行排序而不会丢失键



我有这个改造响应体作为LinkedHashMap<字符串,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"
}
}

我需要按"注意当前时间"值排序。到目前为止,这就是获取排序值数组的方式。

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

但是,这仅返回排序值,而不返回键,这些键现在的顺序错误。有没有办法对LinkedHashMap的值进行排序并保持键的正确顺序?任何和所有的帮助将不胜感激。

您可以将映射转换为(键值对(列表,对其进行排序,然后将其转换回来。

我真的不知道您的示例 Map 值类型中Json什么类型。但是你会在sortedBylambda中转换它,但是对于获得你的长日期是必要的。

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

最新更新