See how to use the rotate method in Collections to rotate the elements to a specified position.
import java.util.*;
public class UsingRotateInCollections {
public static void main(String args[])
{
UsingRotateInCollections usingRotateInCollections = new UsingRotateInCollections();
usingRotateInCollections.proceed();
}
private void proceed()
{
//Creating a list with default values
List defaultList = new ArrayList();
defaultList.add(1);
defaultList.add(2);
defaultList.add(3);
defaultList.add(4);
defaultList.add(5);
defaultList.add(6);
defaultList.add(7);
defaultList.add(8);
System.out.println("List as added: " + Arrays.toString(defaultList.toArray()));
Collections.rotate(defaultList, 2); //Rotating the list elements by 2 positions
System.out.println("List after rotate with 2 positions: "+Arrays.toString(defaultList.toArray()));
}
}
/*
Expected output:
[root@mypc]# java UsingRotateInCollections
List as added: [1, 2, 3, 4, 5, 6, 7, 8]
List after rotate with 2 positions: [7, 8, 1, 2, 3, 4, 5, 6]
*/