Kotlin code to sort list of objects with property(attribute)

Kotlin code to sort list is just a single line code. In this example we sort list of news in descending order on the basis of unixtime attribute of news.

News.kt


import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "news")
data class News (
        @PrimaryKey
        var id: Long? = 0,
        var title: String? = null,
        var feature_image: String? = null,
        var detail: String? = null,
        var source: String? = null,
        var link: String? = null,
        var unixtime: Long = 0,
        )

code to sort news list:

// creat array list
var newsList = ArrayList<News>()

// create news and add to above newsList
var news1 = News()
news1.id = 1
news1.title = "title1"
news2.unixtime = 1000
newsList.add(news1)

var news2 = News()
news2.id = 2
news2.title = "title2"
news2.unixtime = 2000
newsList.add(news2)

var news3 = News()
news3.id = 3
news3.title = "title3"
news3.unixtime = 3000
newsList.add(news3)

var sortedNewsList = newsList.sortedByDescending { it.unixtime }