Monday, June 8, 2026
HomeLanguagesJavaSwapping items of a list in Java : Collections.swap() with Example

Swapping items of a list in Java : Collections.swap() with Example

java.util.Collections.swap() method is a java.util.Collections class method. It swaps elements at the specified positions in given list.

// Swaps elements at positions "i" and "j" in myList.
public static void swap(List mylist, int i, int j)

It throws IndexOutOfBoundsException if either i
or j is out of range.




// Java program to demonstrate working of Collections.swap
import java.util.*;
  
public class GFG
{
    public static void main(String[] args)
    {
        // Let us create a list with 4 items
        ArrayList<String>  mylist =
                        new ArrayList<String>();
        mylist.add("code");
        mylist.add("practice");
        mylist.add("quiz");
        mylist.add("neveropen");
  
        System.out.println("Original List : \n" + mylist);
  
        // Swap items at indexes 1 and 2
        Collections.swap(mylist, 1, 2);
  
        System.out.println("\nAfter swap(mylist, 1, 2) : \n"
                           + mylist);
  
        // Swap items at indexes 1 and 3
        Collections.swap(mylist, 3, 1);
  
        System.out.println("\nAfter swap(mylist, 3, 1) : \n"
                           + mylist);
    }
}


Output:

Original List : Original List : 
[code, practice, quiz, neveropen]

After swap(mylist, 1, 2) : 
[code, quiz, practice, neveropen]

After swap(mylist, 3, 1) : 
[code, neveropen, practice, quiz]

This article is contributed by Mohit Gupta. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.
.

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS