Java Programming Tutorials

Java programming tutorials with many code examples!

Java rotate List

Problem:

How in Java rotate List elements or move an element to specified position? Java Collections Framework has nice solutions for this problem.

Solution:

In the following example we use Collections.rotate(List), from java.util package, to rotate List elements by specified number of positions:

package com.farenda.java;

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

public class CollectionsRotate {

    public static void main(String[] args) {
        List<String> items = Arrays.asList("a", "b", "c", "d", "e");
        System.out.println("Items: " + items);

        forwardBy(items, 1);

        forwardBy(items, 1);

        backwardBy(items, 2);

        moveXbyY(items, 1, 3);
    }

    private static void moveXbyY(List<String> items, int x, int y) {
        String e = items.get(x);
        // +1 because index 'to' is exclusive
        Collections.rotate(items.subList(x, x+y+1), -1);
        System.out.printf("Move '%s' by %d: %s%n", e, y, items);
    }

    private static void backwardBy(List<String> items, int distance) {
        Collections.rotate(items, -distance);
        System.out.printf("Backward %d: %s%n", distance, items);
    }

    private static void forwardBy(List<String> items, int distance) {
        Collections.rotate(items, distance);
        System.out.printf("Forward %d: %s%n", distance, items);
    }
}

As you can see, to move backward, all you have to do is to provide negative number of steps.

Collections.rotate(List) in conjunction with List.subList(from, to) creates a nice idiom to move an element to specified position. It works fast, because subList creates only a view backed by List, so changes in the view are reflected in the original List.

Here’s the result of running the Java code:

Items: [a, b, c, d, e]
Forward 1: [e, a, b, c, d]
Forward 1: [d, e, a, b, c]
Backward 2: [a, b, c, d, e]
Move 'b' by 3: [a, c, d, e, b]

The Java idiom rotate + subView is worth remembering.

Share with the World!