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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024