kotlin - 排序列表基于字符串日期时间
问题描述
我想根据字符串形式的 UTC DateTime 对列表进行降序排序。
我的课
data class CartEntity( val itemId: String, var itemName: String, var createdDate: String)
在这个 createdDate 是“2020-07-28T14:28:52.877Z”
我试过的
const val UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Collections.sort(list, object : Comparator<CartEntity> {
var f: DateFormat =
SimpleDateFormat(
AppConstants.UTC_FORMAT, Locale.ENGLISH
)
override fun compare(o1: CartEntity?, o2: CartEntity?): Int {
return try {
val firstitem = f.parse(o1?.createdDate!!)
val seconditem = f.parse(o2?.createdDate!!)
firstitem.compareTo(seconditem)
} catch (e: ParseException) {
throw IllegalArgumentException(e)
}
}
})
但仍然按降序排序没有按预期工作
解决方案
在 kotlin 风格中,您可以使用标准库函数(以下习惯用法):
从要排序的列表中创建一个新的排序列表:
fun main() {
val list = listOf<CartEntity>(
CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
)
val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
val sortedList = list.sortedByDescending { format.parse(it.createdDate) }
println(sortedList) // `sortedList` is sorted out list, the `list` is holding the original order
}
对原始列表进行排序(列表应该是可变的):
fun main() {
val list = mutableListOf<CartEntity>(
CartEntity(itemId = "", itemName = "", createdDate = "2020-07-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-09-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-08-28T14:28:52.877Z"),
CartEntity(itemId = "", itemName = "", createdDate = "2020-04-28T14:28:52.877Z"),
)
val format: DateFormat = SimpleDateFormat(AppConstants.UTC_FORMAT, Locale.ENGLISH)
list.sortByDescending { format.parse(it.createdDate) }
println(list) // `list` is sorted out list
}
推荐阅读
- python - 将 OCR 从每个图像中检索到的文本写入与每个图像对应的单独文本文件
- powershell - Azure DevOps 获取当前用户 ObjectId
- sql - 如何根据不同的条件添加group by子句?
- c++ - 未定义的行为或 gcc 优化错误
- webgl - Foveated Rendering:WebGL 能否将顶点/片段着色器从屏幕中心渲染到螺旋向外?
- mysql - 如何改进查询以使某些玩家有一段时间没有玩玩家的排名仍然正确?
- haskell - 为什么使用组合运算符可以避免显式引用初始参数的需要?
- snakemake - 如何使用输出目录来聚合文件(并接收更多信息错误消息)?
- duplicati - Duplicati 恢复和零字节文件
- jquery - 如何使用 jquery 显示选定选择的名称?