Home > Enterprise >  Kotlin. ArrayList, how to move element to first position
Kotlin. ArrayList, how to move element to first position

Time:08-17

I have a list of Lessons. Here is my Lessons class:

data class Lessons(
 val id: Long,
 val name: String,
 val time: Long,
 val key: String
)

I need to move the element to the beginning of the list, whose key field has a value "priority". Here is my code:

   val priorityLesson = lessons.find { it.key == "priority" }
        
        if (priorityLesson != null) {
            lessons.remove(priorityLesson)
            lessons.add(0, priorityLesson)
        }

Everything is working but I do not like this solution, perhaps there is a more efficient way to perform this algorithm. In addition, it comes to me to convert the list to mutable, and I would like to leave it immutable.

Please help me.

CodePudding user response:

One way is to call partition() to split the list into a list of priority lesson(s), and a list of non-priority lessons; you can then rejoin them:

val sorted = lessons.partition{ it.key == "priority" }
                    .let{ it.first   it.second }

As well as handling the case of exactly one priority lesson, that will cope if there are none or several. And it preserves the order of priority lessons, and the order of non-priority lessons.

(That will take a little more memory than modifying the list in-place; but it scales the same — both are

  • Related