Java - List Shuffling, Reversing, Swapping, and Rotating


Shuffling gives you a random permutation of the elements in a List.

You shuffle the List by using the Collections.shuffle() static method.

You can supply a java.util.Random object or the shuffle() method can use a default randomizer.

The two versions of the shuffle() methods are as follows:

void shuffle(List<?> list)
void shuffle(List<?> list, Random rnd)


Reversing puts the elements of a List in the reverse order.

You can use the following reverse() static method of the Collections class to accomplish this:

void reverse(List<?> list)

Swapping swaps the position of two elements in a List.

You can perform swapping using the swap() static method of the Collections class, which is defined as follows:

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

i and j are indexes of two elements to be swapped and they must be between 0 and size ? 1, where size is the size of the List.

Example for swap:

Collections.rotate(list.subList(1, 4), 1);

The following code shows how to reorder elements of a List using these methods.


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();

    System.out.println("List: " + list);

    // Shuffle//from  w w w  .  j a v  a 2 s. c o  m
    System.out.println("After Shuffling: " + list);

    // Reverse the list
    System.out.println("After Reversing: " + list);

    // Swap elements at indexes 1 and 3
    Collections.swap(list, 1, 3);
    System.out.println("After Swapping (1 and 3): " + list);

    // Rotate elements by 2
    Collections.rotate(list, 2);
    System.out.println("After Rotating by 2: " + list);