dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Explore the Java Collections Rotate Method

See how to use the rotate method in Collections.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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]

*/ 

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date