In this example tutorials, I am going to show you how to rotate elements in List.

Rotate Elements in List :

We can rotate elements in Java.util.List by using the Collections.rotate(List<?> list, int distance) method.

The Collections.rotate(List<?> list,int distance) method rotates the elements in the given list by the given distance.

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

The Collections.rotate(List<?> list,int distance) method doesn’t effect on the size of the List.

[/box]

[java]

package com.onlinetutorialspoint.javaprograms;

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

public class Rotate_Array {
    public static void main(String[] args) {
        List<String> items = new ArrayList();
        items.add("a");
        items.add("z");
        items.add("c");
        items.add("m");
        items.add("k");
        items.add("n");
        
        Collections.rotate(items,2);
        items.forEach(System.out::println);
    }
}

[/java]

[box type=”success” align=”alignleft” class=”” width=”100%”]

k
n
a
z
c
m

[/box]

Happy Learning 🙂