Swap two elements of a List in Kotlin
This article explores different ways to swap two elements of a list in Kotlin.
1. Using Collections.swap() function
The Collections.swap() function swaps the elements at the specified positions in the specified list. It can be used as follows:
|
1 2 3 4 5 6 7 |
import java.util.* fun main() { val nums = listOf(1, 2, 3, 4, 5) Collections.swap(nums, 1, 3) println(nums) } |
Output:
[1, 4, 3, 2, 5]
If your input is an array, you can use the Collections.swap() function to swap two elements in it. Since the Collections.swap() function accepts a list, you can get a fixed-size list “backed” by the array. Now any changes made to the backed list are reflected in the array as well.
|
1 2 3 4 5 6 7 |
import java.util.* fun main() { val nums = arrayOf(1, 2, 3, 4, 5) Collections.swap(nums.asList(), 1, 3) println(nums.contentToString()) } |
Output:
[1, 4, 3, 2, 5]
2. Using Custom Logic
You can write your utility function for swapping two elements in a list. This can be implemented as follows:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> swap(list: MutableList<T>, i: Int, j: Int) { val t = list[i] list[i] = list[j] list[j] = t } fun main() { val nums = mutableListOf(1, 2, 3, 4, 5) swap(nums, 1, 3) println(nums) } |
Output:
[1, 4, 3, 2, 5]
Here’s an equivalent way to do it for arrays:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun <T> swap(arr: Array<T>, i: Int, j: Int) { val t = arr[i] arr[i] = arr[j] arr[j] = t } fun main() { val nums = arrayOf(1, 2, 3, 4, 5) swap(nums, 1, 3) println(nums.contentToString()) } |
Output:
[1, 4, 3, 2, 5]
That’s all about swapping two elements of a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)