devxlogo

Explore the Java Collections Rotate Method

Explore the Java Collections Rotate Method

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 UsingRotateInCollectionsList as added: [1, 2, 3, 4, 5, 6, 7, 8]List after rotate with 2 positions: [7, 8, 1, 2, 3, 4, 5, 6]*/ 
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist