How do I rotate elements of a collection?

This example demonstrate how to rotate the elements of a collection object. We can use the java.util.Collections class and call the rotate() method with the collection to rotate and the distance as the parameters.

package org.kodejava.util;

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

public class CollectionRotate {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();

        // Add some items into the collection
        for (int i = 0; i < 25; i++) {
            numbers.add(i);
        }

        // Print the collection items        
        System.out.println(Arrays.toString(numbers.toArray()));

        // Rotates the elements in the collection by the 10.
        Collections.rotate(numbers, 10);

        // Print the rotated collection items
        System.out.println(Arrays.toString(numbers.toArray()));
    }
}

Here is the program result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.