listkotlinmutablelist

How to swap elements in MutableList in Kotlin?


I have a list with data that I pull from api. However, I need to make changes on this list (movieList). I need to swap the element at index 0 with the element at index 1. For example:

list[0] = movieA,
list[1] = movieB

then

list[0] = movieB,
list[1] = movieA

The class I intend to do these operations is below:

data class MovieListDto(
    val docs: List<Movie>,
    val limit: Int,
    val offset: Int,
    val page: Int,
    val pages: Int,
    val total: Int
)

fun MovieListDto.MovieListDtoToMovieList(): List<Movie> {
    val movieList = mutableListOf<Movie>()

    for (movie in docs) {
        if (movie._id == "5cd95395de30eff6ebccde5c" ||
            movie._id == "5cd95395de30eff6ebccde5b" ||
            movie._id == "5cd95395de30eff6ebccde5d"
        ) {
            movieList.add(movie)
        }
    }
    return movieList
}

How can I do this?


Solution

  • You could use a simple extension function for that:

    fun <T> MutableList<T>.swap(index1: Int, index2: Int){
        val tmp = this[index1]
        this[index1] = this[index2]
        this[index2] = tmp
    }
    

    it can be use like this:

    list.swap(0, 1)