- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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]
- Related Articles
- Java Program to Rotate Elements of a List
- Java Program to Rotate Matrix Elements
- Java Program to Compare Elements in a Collection
- Java Program to Shuffle the Elements of a Collection
- Append all elements of another Collection to a Vector in Java
- Add elements to LinkedHashMap collection in Java
- Retrieving Elements from Collection in Java- Iterator
- Retrieving Elements from Collection in Java- ListIterator
- Retrieving Elements from Collection in Java- EnumerationIterator
- Append all elements of other Collection to ArrayList in Java
- Golang program to rotate elements of a slice
- Rotate a List in Java
- In how many ways you can retrieve the elements of a collection in Java?
- Retrieving Elements from Collection in Java- For-each loop
- How to retain elements from a Collection in another Collection

Advertisements