Home > Software engineering >  Grouping date list with .groupBy not working on date format "YYYY-mm-dd", gives a strange
Grouping date list with .groupBy not working on date format "YYYY-mm-dd", gives a strange

Time:04-16

I want to group a list of images by day (and change the order asc/desc, which is working). I have the following code below which gets the date in the format YYYY-mm-dd, but when I output the list it's not sorted correctly, I get this as output:

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

I don't know why it's sorted with the most newest date below. If I sort it again from oldest to newest, it gives me the list reversed. So the newest date is on top of the list. I think I'm doing something wrong in the ".groupBy" but I have no idea, it should sort the group on the date string I presume, no?

My code is the following:

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 {
        ...
    }
}

Thanks for your help!

CodePudding user response:

Try to sort the images by key after they have been groupped with the toSortedMap method:

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

CodePudding user response:

groupBy returns a map and to sort a map is tricky.

I suggest sorting the group keys separately, then iterating over the sorted keys:

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

I wrote from memory so tweak the code if it's not compiling

  • Related