使用 .groupBy 对日期列表进行分组,日期格式 "YYYY-mm-dd" 不起作用,给出了一个奇怪的输出 [Kotlin]
Grouping date list with .groupBy not working on date format "YYYY-mm-dd", gives a strange output [Kotlin]
我想按天对图像列表进行分组(并更改顺序 asc/desc,这是可行的)。我有以下代码以 YYYY-mm-dd 格式获取日期,但是当我输出列表时它没有正确排序,我将其作为输出:
2021-09-21
2021-09-21
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2021-09-22
2021-09-22
2021-09-22
我不知道为什么它在下面按最新日期排序。如果我再次从最旧到最新对它进行排序,它会给我颠倒的列表。所以最新的日期在列表的顶部。
我想我在“.groupBy”中做错了什么,但我不知道,它应该根据我认为的日期字符串对组进行排序,不是吗?
我的代码如下:
images.let {
if (orderByAsc) it.reversed()
else it
}
.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}.forEach { (groupKey, group) ->
item {
...
}
}
感谢您的帮助!
groupBy
returns 地图和排序地图是棘手的。
我建议分别对组键进行排序,然后迭代排序后的键:
images.let {
if (orderByAsc) it.reversed()
else it
}
.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}.let { groupedImages ->
val keyList = groupedImages.keySet().toList()
val sortedKeys = if (orderByAsc) keyList.sorted() else keyList.sortedDescending()
sortedKeys.forEach { key ->
val items = groupedImages[key]
// Do something with items
}
}
我凭记忆写的,所以如果它没有编译,请调整代码
使用 toSortedMap
方法对 images
进行分组后,尝试按键对它们进行排序:
val grouppedImages = images.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}
if (orderByAsc) grouppedImages.toSortedMap()
else grouppedImages.toSortedMap(Comparator.reverseOrder())
我想按天对图像列表进行分组(并更改顺序 asc/desc,这是可行的)。我有以下代码以 YYYY-mm-dd 格式获取日期,但是当我输出列表时它没有正确排序,我将其作为输出:
2021-09-21
2021-09-21
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2018-06-28
2021-09-22
2021-09-22
2021-09-22
我不知道为什么它在下面按最新日期排序。如果我再次从最旧到最新对它进行排序,它会给我颠倒的列表。所以最新的日期在列表的顶部。 我想我在“.groupBy”中做错了什么,但我不知道,它应该根据我认为的日期字符串对组进行排序,不是吗?
我的代码如下:
images.let {
if (orderByAsc) it.reversed()
else it
}
.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}.forEach { (groupKey, group) ->
item {
...
}
}
感谢您的帮助!
groupBy
returns 地图和排序地图是棘手的。
我建议分别对组键进行排序,然后迭代排序后的键:
images.let {
if (orderByAsc) it.reversed()
else it
}
.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}.let { groupedImages ->
val keyList = groupedImages.keySet().toList()
val sortedKeys = if (orderByAsc) keyList.sorted() else keyList.sortedDescending()
sortedKeys.forEach { key ->
val items = groupedImages[key]
// Do something with items
}
}
我凭记忆写的,所以如果它没有编译,请调整代码
使用 toSortedMap
方法对 images
进行分组后,尝试按键对它们进行排序:
val grouppedImages = images.groupBy {
// Make a YYYY-mm-dd format from YYYY-mm-dd HH:mm:ss format
it.timestamp.substring(0, min(it.timestamp.length, 10))
}
if (orderByAsc) grouppedImages.toSortedMap()
else grouppedImages.toSortedMap(Comparator.reverseOrder())