Rotate elements of a collection in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live  Demo

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]
raja
Published on 09-Jan-2019 12:32:06
Advertisements