Kinjal
Kinjal

Reputation: 456

Sorting custom object List in kotlin

interface Feed

class Memo : Feed {
    var memoId: String? = null
    var updateTime: String? = null
//    other fileds
}

class Activity : Feed {
    var activityId: String? = null
    var updateTime: String? = null
//    other fileds
}

As above code, I have Created one interface and extend it in the other two classes.

   var mainFeedList: ArrayList<Feed> = ArrayList()
   var memoList: ArrayList<Memo> = ArrayList()
   var ActivityList: ArrayList<Activity> = ArrayList()

    fun arrangeFeedDataOrder() {
   
        mainFeedList.addAll(memoList)
        mainFeedList.addAll(ActivityList)

        mainFeedList.sortedBy {
            when (it) {
                is Activity -> {
                    it.updateTime
                }
                is Memo -> {
                    it.updateTime
                }
                else -> {
                    null
                }
            }
        }
//        Not work above code for sorting
    }

I have the main list which contains memos and activity data. I want to sort this list with updateTime filed. I used sortedBy function but it does not work in my case. Anyone has an idea how to sort the list?

Upvotes: 2

Views: 1546

Answers (1)

cactustictacs
cactustictacs

Reputation: 19622

You want sortBy (sorts the list in place) instead of sortedBy (returns a sorted copy, which you're basically discarding)

Also, why not put updateTime in the interface if it's something common to all Feeds? That way you don't need to do any type checking - you have a list of Feeds, they have an updateTime, so you can just sort by it.updateTime on all of them:

interface Feed {
    var updateTime: String?
}

class Memo : Feed {
    var memoId: String? = null
    override var updateTime: String? = null
}

class Activity : Feed {
    var activityId: String? = null
    override var updateTime: String? = null
}

...

mainFeedList.sortBy { it.updateTime } // or sortBy(Feed::updateTime)

or if you have a superclass for those classes, you could just define the property in there with the default null value (can't do that in an interface, which is why you need to override and provide a value in each class that implements it)

Upvotes: 4

Related Questions