Laura
Laura

Reputation: 432

Sort nested list objects

I'm new to Kotlin and I have the following task. I have a list of objects (Album) which contains fields and a list with another object (Song). I need to sort both album and song lists with their properties. What I tried so far

albumList.onEach { it.songs.sortedByDescending { song -> song.isFavorite} 
.sortedByDescending { it.createDate }

As a result, the album list is sorted by it's createDate property but songs list doesn't. Is there something I'm missing? Thanks

Upvotes: 1

Views: 1436

Answers (2)

ssindher11
ssindher11

Reputation: 247

You can first sort the parent list, and then create a new list by using map on the first list, and inside it, you can use the copy function to set the sorted inner list.

val tempList: List<Album> = albumList
    .sortedWith(compareBy { it.createDate })
val newList = tempList.map { album ->
    val sortedSongs = album.songs.sortedWith(compareBy { it.isFavorite })
    album.copy(songs = sortedSongs)
}

This way, you can prevent using var instead of val :)

Upvotes: 0

Boken
Boken

Reputation: 5446

I found some "dirty" solution. I'm not so happy with that, but it works.

val newList: List<Album> = albumList
    // Sort albums
    .sortedWith(compareBy { it.createDate })
    // Sort songs inside each of albums
    .map { album ->
        album.apply {
            // Assign NEW list
            songs = album.songs.sortedWith(compareBy { it.isFavorite })
        }
    }

How it works:

1) Sort albums by date of creation createDate

2) For each of albums:

  • get all songs
  • map them to itself but only with songs sorting (assign sorted songs to songs field, so it has to be var not val)

Upvotes: 2

Related Questions