Home > Mobile >  How to swap elements in MutableList in Kotlin?
How to swap elements in MutableList in Kotlin?

Time:11-12

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?

CodePudding user response:

val temp = movieList[0]
movieList[0] = movieList[1]
movieList[1] = temp

CodePudding user response:

I think you can use also scope function to swap

movieList[0] = movieList[1].also { movieList[1] = movieList[0] }

CodePudding user response:

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)
  • Related