The following example shows how to use Collections.rotate API.
It rotates the elements in the specified list by the specified distance.
This API can be used to perform both rotate right and rotate left operations.
System.out.println();
System.out.println("Initial list : " + strList);
Collections.rotate(strList, 8);
//This is as good as
//Collections.rotate(strList, 8 % strList.size() );
//Collections.rotate(strList, 8 % 5 );
//Collections.rotate(strList, 3);
System.out.println("Rotate right by 8 positions : " + strList);
Collections.rotate(strList, -9);
//This is as good as
//Collections.rotate(strList, -(9 % strList.size()) );
//Collections.rotate(strList, -(9 % 5) );
//Collections.rotate(strList, -4);
System.out.println("Rotate right by -9 positions : " + strList);
}
}
It gives the following output,
Initial list : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Rotate right by 2 positions : [8, 9, 1, 2, 3, 4, 5, 6, 7]
Rotate left by 4 positions : [3, 4, 5, 6, 7, 8, 9, 1, 2]
Initial list : [A, B, C, D, E]
Rotate right by 8 positions : [C, D, E, A, B]
Rotate right by -9 positions : [B, C, D, E, A]