List rotation demo

In this post under Java Collections, I will explain with example how to rotate elements in a list.

Java “Collections” utility class has static method named “rotate” which will rotate elements in a list.

This method takes two arguments.
1) the list
2) integer representing the distance

Below is the complete main class for your reference

Main class

package core.collection;

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

public class ListRotateDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(0);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        System.out.println("Before rotation: " + list.toString());
        Collections.rotate(list, 2);
        System.out.println("After rotation: " + list.toString());
    }
}

In the above code, I have created a list of type parameter “Integer” and added elements.

At line 17, I am calling “Collections” static method “rotate” and passing the list and integer 2 as arguments.

Integer 2, represents the distance, the elements has to travel.

In other words, we are saying Java Collections to rotate every element in the list two positions ahead.

In this way, we can rotate elements in the list.

Below is the output

Output

Before rotation: [1, 2, 3, 4, 5]
After rotation: [4, 5, 1, 2, 3]

Leave a comment