tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collections > Collection Rotate

Collection Rotate 

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.

File Name  :  
com/bethecoder/tutorials/utils/collections/CollectionsRotate.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsRotate {

  public static void main (String [] args) {
    
    List<Integer> intList = Arrays.asList(new Integer [] {
        12345678
    });
    
    System.out.println("Initial list : " + intList);
    
    Collections.rotate(intList, 2);
    System.out.println("Rotate right by 2 positions : " + intList);
    
    Collections.rotate(intList, -4);
    System.out.println("Rotate left by 4 positions : " + intList);
    
    
    List<String> strList = Arrays.asList(new String [] {
        "A""B""C""D""E"
    });
    
    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]



 
  


  
bl  br