英文:
kotlin how to sort List<Map<String, Any>>?
问题
我想根据项目date
对rawData进行排序
val rawData: List<Map<String, Any>> = parseSampleData()
val sortData = rawData.sortedBy { it["date"] as Comparable<Any> }
然后在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>
同时这个也不起作用
val sortedList = rawData.sortedWith(compareBy({ it.get("date") as Comparable<Any> }))
带有这个错误
Type mismatch.
Required:
Comparable<*>
Found:
Any?
请帮忙
英文:
I want sort rawData according to the item date
val rawData: List<Map<String, Any>> = parseSampleData()
val sortData = rawData.sortedBy { it["date"] }
then error in sortedBy
like this
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
答案1
得分: 0
你所面临的问题是,Kotlin 不知道如何对类型为 Any?
的对象进行排序,而 it["date"]
和 it.get("date")
返回的就是这种类型。如果你知道 it["date"]
返回的类型,那么可以将其转换为该类型,前提是它实现了 Comparable
接口(我假设它是某种可比较的日期对象)。否则,你需要指定映射值中包含的内容(同样要求它实现了 Comparable
接口)。
英文:
The issue that you are facing is that kotlin doesn't know how to sort objects of type Any?
, which is what is returned by it["date"]
and 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). Otherwise you need to specity what your map contains in the value slot (again provided taht it implements Comparable
).
答案2
得分: 0
你需要将日期转换为 LocalDate
或 ZonedDateTime
,然后可以进行比较。
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")),
)
英文:
You'll have to convert the date to either LocalDate
or ZonedDateTime
, which can then be compared.
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")),
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论