
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rotate Elements of a Collection in Java
To rotate elements of a collection in Java, we use the Collections.rotate() method. The rotate method rotates the elements specified in the list by a specified distance. When this method is invoked, the element at index x will be the element previously at index (x - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive.
Declaration − The java.util.Collections.rotate() is declared as follows -
public static void rotate(List<?> list, int distance)
Let us see a program to rotate elements of a collection in Java -
Example
import java.util.*; public class Example { public static void main(String[] args) { List list = new ArrayList(); for (int i = 0; i < 15; i++) { list.add(i); } System.out.println(Arrays.toString(list.toArray())); Collections.rotate(list, 7); System.out.println(Arrays.toString(list.toArray())); } }
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [8, 9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7]
Advertisements