In this post under Java Collections, I will explain with example how to swap elements of an list.
Below is the complete main code for your reference.
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class SwappingListDemo {
8 public static void main(String[] args) {
9 List<Integer> integerList = new ArrayList<>(0);
10 integerList.add(1);
11 integerList.add(2);
12 integerList.add(3);
13 integerList.add(4);
14 integerList.add(5);
15
16 System.out.println("Before swapping: " + integerList);
17
18 Collections.swap(integerList, 1, 3);
19
20 System.out.println("After swapping: " + integerList);
21 }
22 }
In the above code, at line 9, I create an integer list named “integerList” and populate it with elements.
At line 18, we call “Collections” static method “swap” passing the list and index of elements that should be swapped.
In this way we can swap two elements in the list.