Toshu M
Toshu M

Reputation: 1

Sort a mutable list of objects in Kotlin

There is a class name recording with parameters song, artist, and playtime

class Recording {
    var title: String
    var artists: String
    var playingTime: Int

    constructor(t: String, a: String, p: Int) {
        title = t
        artists = a
        playingTime = p
    }
}

I have a mutable list of objects,I need to sort this based on each parameter ie song, artist, and playtime.

 var list = mutableListOf<Recording>(
     Recording("Sorry", "Justin Bieber", 420),
     Recording("a", "a", 1),
     Recording("b", "b", 2)
 )

Upvotes: 0

Views: 1231

Answers (1)

Codemaker2015
Codemaker2015

Reputation: 1

You try it with either sortedWith or sortBy methods to sort a list of objects.

Method 1:

val result = list.sortedWith(compareBy({ it.title }, { it.artists }, {it.playingTime}))

Method 2:

val list1 = list.sortBy { it.title }
val list2 = list.sortBy { it.artists }
val list3 = list.sortBy { it.playingTime }

In the first method you will get a list of sorts lists and the second method will gives you the sorted results in different lists.

Upvotes: 1

Related Questions