简体   繁体   English

kotlin 如何对列表进行排序<Map<String, Any> &gt;?

[英]kotlin how to sort List<Map<String, Any>>?

I want sort rawData according to the item date我想根据项目date对 rawData 进行排序

val rawData: List<Map<String, Any>> = parseSampleData()

val sortData = rawData.sortedBy { it["date"] }

then error in sortedBy like this然后像这样在sortedBy出错

Type parameter bound for R in 

inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy
(
crossinline selector: (T) → R?
)
: List<T>
is not satisfied: inferred type Any is not a subtype of Comparable<Any>

also this not work这也行不通

val sortedList = rawData.sortedWith(compareBy({ it.get("date") }))

with this error有这个错误

Type mismatch.
Required:
Comparable<*>?
Found:
Any?

please help请帮忙

The issue that you are facing is that kotlin doesn't know how to sort objects of type Any?您面临的问题是 kotlin 不知道如何对Any?类型的对象进行排序Any? , which is what is returned by it["date"] and it.get("date") . ,这是it["date"]it.get("date") If you know the type that is returned by it["date"] , then cast it to that type, provided it implements Comparable (I assume it is some kind of a date object which should be comparable).如果您知道it["date"]返回的类型,则将其Comparable转换为该类型,前提是它实现了Comparable (我认为它是某种应该具有可比性的日期对象)。 Otherwise you need to specity what your map contains in the value slot (again provided taht it implements Comparable ).否则,您需要指定您的地图在值槽中包含的内容(再次提供它实现Comparable )。

You'll have to convert the date to either LocalDate or ZonedDateTime , which can then be compared.您必须将日期转换为LocalDateZonedDateTime ,然后可以进行比较。

import java.time.LocalDate

fun main() {
    val rawData: List<Map<String, Any>> = parseSampleData()
    val sortData = rawData.sortedBy { it["date"] as LocalDate }
    println(sortData)
}

fun parseSampleData() = listOf(
    mapOf("date" to LocalDate.parse("2020-01-03")),
    mapOf("date" to LocalDate.parse("2020-01-01")),
    mapOf("date" to LocalDate.parse("2020-01-02")),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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