Swap two elements of a List in Java
This post will discuss how to swap two elements of a List in Java.
1. Using Collections.swap() method
The standard solution to swap two elements in a List is using the Collections.swap() method, which swaps the elements at the specified positions in a list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; import java.util.Collections; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("a", "c", "b", "d"); Collections.swap(words, 1, 2); System.out.println(words); } } |
Output:
[a, b, c, d]
To swap an array, you can get a fixed-size list backed by the array and pass it to the Collections.swap() method. Since the list is backed by the array, any changes made to the list will be visible in the array as well.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Arrays; import java.util.Collections; class Main { public static void main(String[] args) { String[] words = {"a", "c", "b", "d"}; Collections.swap(Arrays.asList(words), 1, 2); System.out.println(Arrays.toString(words)); } } |
Output:
[a, b, c, d]
For primitive arrays, the Arrays.asList() method won’t work, but you can use the Ints.asList() method offered by the Guava library.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.primitives.Ints; import java.util.Arrays; import java.util.Collections; class Main { public static void main(String[] args) { int[] nums = {1, 3, 2, 4}; Collections.swap(Ints.asList(nums), 1, 2); System.out.println(Arrays.toString(nums)); } } |
Output:
[1, 2, 3, 4]
2. Using temporary variable
Another common solution to swap two values in a list is creating your own generic utility function for swapping. This can be done as follows in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Arrays; import java.util.List; class Main { public static final <T> void swap(List<T> list, int i, int j) { T temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); } public static void main(String[] args) { List<String> words = Arrays.asList("a", "c", "b", "d"); swap(words, 1, 2); System.out.println(words); } } |
Output:
[a, b, c, d]
Here’s an equivalent way to do it for arrays:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Arrays; class Main { public static final <T> void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { String[] words = {"a", "c", "b", "d"}; swap(words, 1, 2); System.out.println(Arrays.asList(words)); } } |
Output:
[a, b, c, d]
That’s all about swapping two elements of a List in Java.
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 :)