The Wayback Machine - https://web.archive.org/web/20240927180503/https://www.geeksforgeeks.org/java-program-to-rotate-elements-of-the-list/
Open In App

Java Program to Rotate Elements of the List

Last Updated : 28 Dec, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

List is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. In this article, we are going to see how to rotate elements of a list. Let’s consider the following list.

initial list

ORIGINAL LIST BEFORE ROTATION

There are two types of rotations in a list. They are right rotation and left rotation. After Four Right Rotations the list becomes as shown below:

After four right rotations

LIST AFTER  ROTATING FOUR POSITIONS

Method 1: (Without Using in-built methods)

Working For Right Rotation

  • First store the last element of the list in a temp variable.
  • Move the elements in one position towards the right.
  • Now change the first element value of the list with value in a temp variable.
  • Update the value to a temp variable to the new last element.
  • Repeat the above steps required a number of rotations.

Example:

Java




// Java Program to Rotate Elements of the List
import java.io.*;
import java.util.*;
class GFG {
    
    public static void main(String[] args)
    {
        // creating ArrayList
        List<Integer> my_list = new ArrayList<>();
        my_list.add(10);
        my_list.add(20);
        my_list.add(30);
        my_list.add(40);
        my_list.add(50);
        my_list.add(60);
        my_list.add(70);
  
        // Printing list before rotation
        System.out.println(
            "List Before Rotation : "
            + Arrays.toString(my_list.toArray()));
  
        // Loop according to the number of rotations
        for (int i = 0; i < 4; i++) {
            
            // storing the last element in the list
            int temp = my_list.get(6);
            
            // traverse the list and move elements to right
            for (int j = 6; j > 0; j--) {
                my_list.set(j, my_list.get(j - 1));
            }
            my_list.set(0, temp);
        }
  
        // Printing list after rotation
        System.out.println(
            "List After Rotation :  "
            + Arrays.toString(my_list.toArray()));
    }
}


Output

List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation :  [40, 50, 60, 70, 10, 20, 30]

After Four Left Rotations the list becomes as shown below:

After four left rotations

LIST AFTER ROTATING FOUR POSITIONS

Working For Left Rotation

  • First store the first element of the list in a temp variable.
  • Move the elements in one position towards the left.
  • Now change the last element value of the list with the value in the temp variable.
  • Update the value to a temp variable to the new first element.
  • Repeat the above steps required a number of rotations.

Example

Java




// Java Program to Rotate Elements of the List
  
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // creating array list
        List<Integer> my_list = new ArrayList<>();
        my_list.add(10);
        my_list.add(20);
        my_list.add(30);
        my_list.add(40);
        my_list.add(50);
        my_list.add(60);
        my_list.add(70);
  
        // Printing list before rotation
        System.out.println(
            "List Before Rotation : "
            + Arrays.toString(my_list.toArray()));
  
        // Loop according to the number of rotations
        for (int i = 0; i < 4; i++) {
            // storing the first element in the list
            int temp = my_list.get(0);
            // traverse the list and move elements to left
            for (int j = 0; j < 6; j++) {
                my_list.set(j, my_list.get(j + 1));
            }
            my_list.set(6, temp);
        }
  
        // Printing list after rotation
        System.out.println(
            "List After Rotation :  "
            + Arrays.toString(my_list.toArray()));
    }
}


Output

List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation :  [50, 60, 70, 10, 20, 30, 40]

Method 2: (Rotation Using Collections.rotate(list, distance) method)

Both left and right rotations can be performed directly using Java Collections.

Syntax

Collections.rotate(list_name , distance)

Parameters: 

  • list_name: name of the list.
  • distance: Distance is the number of elements that we have to rotate.

Returns: It returns a rotated list.

Note: Negative Distance gives Left Rotation while Positive gives Right Rotation.

Example: Using Positive distance to get the Right Rotation.

Java




// Java Program to Rotate Elements of the List
  
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // creating array list
        List<Integer> my_list = new ArrayList<>();
        my_list.add(10);
        my_list.add(20);
        my_list.add(30);
        my_list.add(40);
        my_list.add(50);
        my_list.add(60);
        my_list.add(70);
  
        // Printing list before rotation
        System.out.println(
            "List Before Rotation : "
            + Arrays.toString(my_list.toArray()));
  
        // Rotating the list at distance 4
  
        Collections.rotate(my_list, 4);
  
        // Printing list after rotation
        System.out.println(
            "List After Rotation :  "
            + Arrays.toString(my_list.toArray()));
    }
}


Output

List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation :  [40, 50, 60, 70, 10, 20, 30]

Example: Using Negative distance to get the Left Rotation.

Java




// Java Program to Rotate Elements of the List
  
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        // creating array list
        List<Integer> my_list = new ArrayList<>();
        my_list.add(10);
        my_list.add(20);
        my_list.add(30);
        my_list.add(40);
        my_list.add(50);
        my_list.add(60);
        my_list.add(70);
  
        // Printing list before rotation
        System.out.println(
            "List Before Rotation : "
            + Arrays.toString(my_list.toArray()));
  
        // Rotating the list at distance -3
        Collections.rotate(my_list, -4);
  
        // Printing list after rotation
        System.out.println(
            "List After Rotation :  "
            + Arrays.toString(my_list.toArray()));
    }
}


Output

List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation :  [50, 60, 70, 10, 20, 30, 40]


Previous Article
Next Article

Similar Reads

Java Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Java Program to Rotate Matrix Elements
Matrix is simply a two-dimensional array. So the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices Using naive approach
6 min read
Java Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
4 min read
Java Program to Rotate Matrix Elements
Given a matrix, clockwise rotate elements in it. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The idea is to use loops similar to the program f
3 min read
Java Program to Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Java Program to Rotate Linked List block wise
Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples:  Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explanation: Here blocks of size 3 are rotated towards righ
4 min read
Java Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Java Code import java.util.Arrays; public class Test { static int arr[] = new int[]{1, 2, 3, 4, 5}; // Method for rotation static vo
1 min read
Java Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
3 min read
Java Program to Rotate an Image
The problem statement is to rotate an image clockwise 90 degrees for which here we will be using some in-built methods of BufferedImage class and Color c Classes required to perform the operation is as follows: To read and write an image file we have to import the File class. This class represents file and directory path names in general.To handle
3 min read
Java Program to Rotate digits of a given number by K
Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits. Examples: Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required output is 34512 Input: N = 12345, K = -3Output: 34
2 min read
Java Program to Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
4 min read
Java Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Java Program for Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space.  Examples :  Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that
6 min read
Java Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 The given matr
5 min read
Java Program to Rotate bits of a number
Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at the right end are put back at the left end. Recommen
3 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
How to Left or Right rotate an Array in Java?
Given an array arr[] of size N and D index, the task is to rotate the array by the D index. We have two flexibilities either to rotate them leftwards or rightwards via different ways which we are going to explore by implementing every way of rotating in both of the rotations. Ways: Using temporary arrayRecursively rotating array one by oneUsing Jug
15+ min read
Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
7 min read
Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples: Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6,
5 min read
Java Program to Sort the Elements of the Circular Linked List
In a circular linked list, every node points to its next node in the sequence but the last node points to the first node in the list. Here, Create a circular linked list and sort the circular linked list in ascending order. Circular linked list before sorting: Circular linked list after sorting: Approach: Take two pointers: Current pointing to head
3 min read
Java Program to Combine Two List by Alternatively Taking Elements
A list is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other c
6 min read
Java Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5
4 min read
Java Program For Pairwise Swapping Elements Of A Given Linked List
Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For example, if the linked list is 1->2->3->4->
3 min read
Java Program For Rearranging A Given List Such That It Consists Of Alternating Minimum Maximum Elements
Given a list of integers, rearrange the list such that it consists of alternating minimum-maximum elements using only list operations. The first element of the list should be minimum and the second element should be the maximum of all elements present in the list. Similarly, the third element will be the next minimum element and the fourth element
2 min read
Java Program to Return the Elements at Odd Positions in a List
Given a List, the task is to return the elements at Odd positions in a list. Let's consider the following list. Clearly, we can see that elements 20, 40, 60 are at Odd Positions as the index of the list is zero-based. Now we should return these elements. Approach 1:Initialize a temporary value with zero.Now traverse through the list.At each iterati
3 min read
Program to convert List of Integer to List of String in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes. Using Java 8 Stream API: A Stream is
3 min read
Java Program to Access the Part of List as List
A List is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other c
4 min read
Java Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4 Recommended: Please sol
3 min read
Java Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Program to convert List of String to List of Integer in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and Stack classes. 1. Using Java 8 Stream API: A Strea
3 min read
Article Tags :
Practice Tags :