0

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)
 )
1
  • val sortedList = list.sortedWith(compareBy({ it.title.toLowerCase() }, { it.artists.toLowerCase() }, {it.playingTime})) Commented Jan 13, 2021 at 3:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this will work fine for your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.