如何在 Kotlin 中交换 MutableList 中的元素?
How to swap elements in MutableList in Kotlin?
我有一个列表,其中包含我从 api 中提取的数据。但是,我需要对此列表 (movieList) 进行更改。我需要将索引 0 处的元素与索引 1 处的元素交换。例如:
list[0] = movieA,
list[1] = movieB
然后
list[0] = movieB,
list[1] = movieA
我打算做这些操作的class如下:
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
}
我该怎么做?
val temp = movieList[0]
movieList[0] = movieList[1]
movieList[1] = temp
我认为你可以使用 also
作用域函数来交换
movieList[0] = movieList[1].also { movieList[1] = movieList[0] }
您可以为此使用一个简单的扩展函数:
fun <T> MutableList<T>.swap(index1: Int, index2: Int){
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
可以这样使用:
list.swap(0, 1)
我有一个列表,其中包含我从 api 中提取的数据。但是,我需要对此列表 (movieList) 进行更改。我需要将索引 0 处的元素与索引 1 处的元素交换。例如:
list[0] = movieA,
list[1] = movieB
然后
list[0] = movieB,
list[1] = movieA
我打算做这些操作的class如下:
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
}
我该怎么做?
val temp = movieList[0]
movieList[0] = movieList[1]
movieList[1] = temp
我认为你可以使用 also
作用域函数来交换
movieList[0] = movieList[1].also { movieList[1] = movieList[0] }
您可以为此使用一个简单的扩展函数:
fun <T> MutableList<T>.swap(index1: Int, index2: Int){
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
可以这样使用:
list.swap(0, 1)