【问题标题】:kotlin, how to sort a list and filter out the some object at sametimekotlin,如何对列表进行排序并同时过滤掉某些对象
【发布时间】:2022-11-04 15:46:17
【问题描述】:

对于 kotlin,它有 sortedByDescending 用于对列表进行排序。

如果列表中有一些空对象和一些具有一定值的对象,那么在排序时它想过滤掉那些项目,怎么做?

        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) }

【问题讨论】:

    标签: kotlin sorting filter


    【解决方案1】:

    您可以先过滤掉空值,然后在排序之前过滤掉带有“无效”标签的那些,像这样

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

    您可以像这样组合这两个过滤器,但结果类型仍然是一个包含可为空对象的列表,这意味着您必须稍后添加!!

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

    【讨论】:

    • 谢谢@lvo!可以过滤掉另一个(the object has tag=="invalid")与sortedByDescending()调用相同吗?我猜不是。
    • @lannyf 我完全忽略了标签要求。我添加了更多信息
    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多