Swap two elements in a linked list java

We can use Collections.swap() method to swap two elements in a linked list in java. We have to pass the indexes which we need to swap.

Syntax:

Collections.swap(linkedList, element1, element2);

Example:

package com.w3spoint;
 
import java.util.Collections;
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
	System.out.println("Actual LinkedList:"+linkedList);
	Collections.swap(linkedList, 2, 4);
        System.out.println("Results after swap operation:" + linkedList);
  }
}

Output

Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
Results after swap operation:[Jai, Mahesh, Vishal, Vivek, Naren, Hemant]
Please Share