Home > Software design >  SortBy descending in Kotlin is not working by date
SortBy descending in Kotlin is not working by date

Time:03-02

I'm getting the picture objects from backend - Room database, and I want to sort them in RecyclerView by date - most recent on the top. I'm using kotlin list functions, but the results are this same on both ASC and DESC sort. Why?

Here is my code:

private fun inflateRecyclerView(pictureList: List<FavouritePictureModel>) {
        val list = pictureList.map { picture ->
            picture.id.let {
                id
                FavouritePicturesItem(
                    id = id,
                    copyright = picture.copyright,
                    date = dateStringToDate(picture.date),
                    explanation = picture.explanation,
                    title = picture.title,
                    url = picture.url,
                    bitmap = picture.bitmap,
                )
            }
        }
        list.sortedBy { it.date }
        Timber.d("Sorted ASC: $list")
        list.sortedByDescending{ it.date }
        Timber.d("Sorted DESC: $list")
        
        adapter.submitList(list)
    }

@SuppressLint("SimpleDateFormat")
private fun dateStringToDate(date: String): Date {
    return SimpleDateFormat("yyyy-MM-dd").parse(date)
}

CodePudding user response:

sortedBy doesn't sort the list itself but returns a new list with the sorting. so you need to save the result to the old list, like

list = list.sortedBy { it.date }

You would need to make it a var then though. Or alternatively directly pass the sorted list to the submitList like

adapter.submitList(list.sortedBy { it.date })
  • Related