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.

Download  Run Code

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.

Download  Run Code

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.

Download Code

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:

Download  Run Code

Output:

[a, b, c, d]

 
Here’s an equivalent way to do it for arrays:

Download  Run Code

Output:

[a, b, c, d]

That’s all about swapping two elements of a List in Java.