To rotate elements in a list in Java, you can use the Collections.rotate()
method.
In this example,
numbers
with integer values.Collections.rotate()
method to rotate the elements by a specified distance.import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
int distance = 2;
Collections.rotate(numbers, distance);
System.out.println("Rotated list: " + numbers);
}
}
Rotated list: [4, 5, 1, 2, 3]
In this example,
words
with string values.Collections.rotate()
method to rotate the elements by a specified distance.import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "banana", "cherry", "date", "elderberry"));
int distance = 3;
Collections.rotate(words, distance);
System.out.println("Rotated list: " + words);
}
}
Rotated list: [cherry, date, elderberry, apple, banana]
In this tutorial, we learned How to Rotate Elements in a List in Java language with well detailed examples.