Rotating the elements in the specified list by the specified distance

Rotating the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (This method has no effect on the size of the list.)

For example, suppose list comprises [t, a, n, k, s]. After invoking Collections.rotate(list, 1) (or Collections.rotate(list, -4)), list will comprise [s, t, a, n, k].


package collection.demos;



import java.util.ArrayList;

import java.util.Collections;



public class RotatingElementsInList {

    public static void main(String[] args) {

        ArrayList<String> items=new ArrayList<String>();

        items.add("A");

        items.add("B");

        items.add("C");

        items.add("D");

        items.add("E");

        System.out.println("Initial Elements : "+items);

        Collections.rotate(items, 2);

        System.out.println("After rotated    : "+items);

    }

}

/*

 OUTPUT :

 Initial Elements : [A, B, C, D, E]

 After rotated    : [D, E, A, B, C]

 */

No comments:

Popular Posts