Swap elements of ArrayList with Java collections

Java 8Object Oriented ProgrammingProgramming

In order to swap elements of ArrayList with Java collections, we need to use the Collections.swap() method. It swaps the elements at the specified positions in the list.

Declaration −The java.util.Collections.swap() method is declared as follows −

public static void swap(List <?> list, int i, int j)

where i is the index of the first element to be swapped, j is the index of the other element to be swapped and list is the list where the swapping takes place.

Let us see a program to swap elements of ArrayList with Java collections −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(20);
      list.add(30);
      list.add(40);
      list.add(50);
      System.out.println("Original list : " + list);
      Collections.swap(list, 3, 1); // swapping element at index 3 i.e. 40 and index 1 i.e. 20
      System.out.println("List after swapping : " + list);
   }
}

Output

Original list : [10, 20, 30, 40, 50]
List after swapping : [10, 40, 30, 20, 50]
raja
Published on 08-Jan-2019 13:24:28
Advertisements