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]
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023