Java Utility Library

Java Collections - sort() Method



The java.util.Collections.sort() method is used to swap the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Syntax

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

Parameters

list Specify the list in which to swap elements.
i Specify the index of one element to be swapped.
j Specify the index of the other element to be swapped.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >= list.size()).

Example:

In the example below, the java.util.Collections.sort() method is used to reverse the order of elements in a given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object
    List<Integer> MyList = new ArrayList<Integer>();

    //populating the list
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    //printing the list
    System.out.println("MyList contains: " + MyList); 

    //reverse the order of elements in the list
    //using swap elements
    int i = 0; 
    int j = MyList.size()-1;
    while(j > i) {
      Collections.swap(MyList, i, j);
      i++;
      j--;
    }

    //printing the list again
    System.out.println("MyList contains: " + MyList);   
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40, 50]
MyList contains: [50, 40, 30, 20, 10]

❮ Java.util - Collections