How Java Collections.rotate method works

How Java Collections.rotate method works:

java.util.Collections class comes with a lot of useful methods that can beused with any collection object like list, vector, HashSet, HashMap etc. In this post, we will learn how to use the rotate method defined in java.util.Collections. This method is used to rotate the contents in a list. It is defined as below:

Syntax of Collections.rotate :

This method is defined as below:

public static void rotate(List<?> list, int distance)

Here,

  • list is the given list
  • distance is the distance that we are rotating the list.

It will change the list by moving the element to index i from (i - distance) mod listSize.

It doesn’t return anything or its return type is void. Also, it is a static method i.e. we can call this method directly on Collections class.

The value of distance can be negative, zero or greater than the size of the list.

Exception:

It throws one exception UnsupportedOperationException if the specified list doesn’t support set operation.

Example of Collections.rotate:

Let’s take a look at the below example. We are using Collection.rotate to rotate the ArrayList :

import java.util.*;

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

        for (int i = 1; i < 10; i++) {
            intList.add(i);
        }

        System.out.println("ArrayList before rotate "+intList);

        Collections.rotate(intList, 3);
        System.out.println("Rotate distance 3 "+intList);

        Collections.rotate(intList, -2);
        System.out.println("Rotate distance -2 "+intList);

        Collections.rotate(intList, 0);
        System.out.println("Rotate distance 0 "+intList);

        Collections.rotate(intList, 9);
        System.out.println("Rotate distance 9 "+intList);
    }
}

In this example, we are doing rotate operation on the linked list. It will print the below output:

ArrayList before rotate [1, 2, 3, 4, 5, 6, 7, 8, 9]
Rotate distance 3 [7, 8, 9, 1, 2, 3, 4, 5, 6]
Rotate distance -2 [9, 1, 2, 3, 4, 5, 6, 7, 8]
Rotate distance 0 [9, 1, 2, 3, 4, 5, 6, 7, 8]
Rotate distance 9 [9, 1, 2, 3, 4, 5, 6, 7, 8]
  • The first rotate moves all elements to right direction by 3
  • The second rotate moves all elements to left direction by 2
  • The third rotate doesn’t change any position of the elements because the distance is 0
  • The fourth rotate also not changing any position of the elements because we are rotating it with a distance equal to the size of the array list.

Collections.rotate with Array to rotate an array:

We can’t rotate an array but we can convert one array to a list and rotate it.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Integer intArr[] = {1,2,3,4,5,6,7};

        List<Integer> arrList = Arrays.asList(intArr);
        Collections.rotate(arrList, 3);
    }
}

You might also like: