Java Collections.rotate()

Written by: Arvind Rai,
Last updated:
September 05, 2021
On this page we will learn static method rotate() of Java java.util.Collections class. The Collections.rotate() method rotates the elements of a Java list for the given distance. We can also rotate the sublist for the given distance within a list. Find its method syntax.
public static void rotate(List<?> list,  int distance) 
The value of distance can be from 0 to list.size() -1. For the example, suppose we have a list {A B C} and if we are rotating the list for the distance -1 and 1 respectively, the result will be as follows.
1. {A   B  C} after rotating for distance= -1
   {B  C  A}

2. {A   B  C} after rotating for distance= 1
   {C  A   B} 
Now find the example.
MyApp.java
package com.concretepage;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MyApp {
    public static void main(String[] args) {
        User u1 = new User("A");
        User u2 = new User("B");
        User u3 = new User("C");
        List<User> list = Arrays.asList(u1,  u2, u3);
        System.out.println("before rotate");
        list.forEach(u -> System.out.print(u.getName()+ " ")); //A B C
        System.out.println("\nafter rotating by distnace 2");
        Collections.rotate(list, 2);
        list.forEach(u -> System.out.print(u.getName()+ " ")); //B C A 
        System.out.println("\nafter rotating by distnace -1");
        Collections.rotate(list, -1);
        list.forEach(u -> System.out.print(u.getName()+ " ")); //C A B         
    }
}
class User {
  private String name;
  public User(String name) {
      this.name = name;
  }
  public String getName() {
      return name;
  }
} 
Find the output.
before rotate
A B C 
after rotating by distnace 2
B C A 
after rotating by distnace -1
C A B  

Collections.rotate with SubList

Now we will rotate a sub list within a list. Find the example.
RotateSubList.java
package com.concretepage;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class RotateSubList {
  public static void main(String[] args) {
	List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
	System.out.println("List before rotate");
        list.forEach(n -> System.out.print(n + " "));
	System.out.println("\nlist.subList(2, 5)");
	list.subList(2, 5).forEach(n -> System.out.print(n + " "));
	System.out.println("\nList after rotating sublist by distnace 1");
	Collections.rotate(list.subList(2, 5), 1);
	list.forEach(n -> System.out.print(n + " "));
  }
} 
Find the output.
List before rotate
1 2 3 4 5 6 7 8 
list.subList(2, 5)
3 4 5 
List after rotating sublist by distnace 1
1 2 5 3 4 6 7 8 

Reference

Collections.rotate()

Join the Newsletter

(Subscribe to get our latest content directly into your inbox)

WRITTEN BY
ARVIND RAI
ARVIND RAI









©2024 concretepage.com | Privacy Policy | Contact Us