lannyf
lannyf

Reputation: 11025

kotlin, how to sort a list and filter out the some object at sametime

With kotlin it has sortedByDescending for sorting a list.

If the list has some null object and some object which has certain value, when do the sorting it would like to filter out those items, how to do it?

        class TheObj (val postTime: Long, val tag: String)

        val srcList = mutableListOf(
            TheObj(2022, "a"),
            TheObj(2020, "b"),
            null,
            TheObj(2021, "c"),
            TheObj(2020, "invalid")
        )
        
        /////////////
        // would like to filter out the null object and the object has tag=="invalid" in the sorted list

        val desSortedList = srcList.sortedByDescending { obj -> obj.postTime }//<== this does not work
        desSortedList.forEach{ s -> println(s.postTime) }

Upvotes: 0

Views: 107

Answers (1)

Ivo
Ivo

Reputation: 23164

You can filter out the nulls first, and then the ones with the "invalid" tag before sorting, like this

val desSortedList = srcList.filterNotNull().filter { it.tag != "invalid" }.sortedByDescending { it.postTime }
desSortedList.forEach{ println(it.postTime) }

You could combine the two filters like this but then you'll have that the resulting type is still a list with nullable objects meaning you have to add !! later on:

val desSortedList = srcList.filter { it != null && it.tag != "invalid" }.sortedByDescending { it!!.postTime }
desSortedList.forEach{ println(it!!.postTime) }

Upvotes: 2

Related Questions