Issue
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
Solution
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 sortedsongs
tosongs
field, so it has to bevar
notval
)
Answered By - Boken
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.