tes*_*van 1 algorithm collections arraylist kotlin data-class
我有一份清单Lessons。这是我的Lessons课程:
data class Lessons(
val id: Long,
val name: String,
val time: Long,
val key: String
)
Run Code Online (Sandbox Code Playgroud)
我需要将元素移动到列表的开头,其key字段的值为“priority”。这是我的代码:
val priorityLesson = lessons.find { it.key == "priority" }
if (priorityLesson != null) {
lessons.remove(priorityLesson)
lessons.add(0, priorityLesson)
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但我不喜欢这个解决方案,也许有一种更有效的方法来执行这个算法。此外,我需要将列表转换为可变的,并且我想将其保留为不可变的。
请帮我。
一种方法是调用partition()将列表拆分为优先课程列表和非优先课程列表;然后你可以重新加入他们:
val sorted = lessons.partition{ it.key == "priority" }\n .let{ it.first + it.second }\nRun Code Online (Sandbox Code Playgroud)\n除了处理只有一门优先课程的情况外,如果没有或有几门优先课程,也可以处理。\xe2\x80\x82并且它保留优先课程的顺序和非优先课程的顺序。
\n(这比就地修改列表需要多一点内存;但是它缩放相同的 \xe2\x80\x94 都是 (n)。\xe2\x80\x82\ 也更容易理解但更难获得错误的!)
\n