Rotate List in JavaA list is an ordered collection of elements that can be stored the duplicate values. List store elements in the same order in which we insert them, so it maintains the insertion order of elements and allows us to access and insertion of elements based on position. In this section, we will understand how we can rotate the elements of the list in Java. Suppose we have the following list to rotate: 1 > 2> 3> 4> 5 > 6 > 7 We can perform rotation in two ways, i.e., Right Rotation and Left Rotation. After performing 4 right rotations, list contains elements in the following order: 4 > 5> 6> 7> 1 > 2 > 3 Right RotationWe can implement right rotation with or without using builtin methods. Let's understand both of the ways one by one: Right Rotation without using a builtin methodRight Rotation is done by shifting elements to the right side of the list. We use the following steps to perform the right Rotation in a list:
Let's implement the code for the above theory to perform right rotation without using the builtin method: RightRotationExample1.java Output: Right Rotation by Using a builtin MethodWe use the rotate() method of the Collections class to perform the right Rotation in the list. The method accepts two parameters, i.e., a list and a positive integer. List parameter defines a list in which we need to perform Rotation. The distance parameter is a positive integer that defines the number of Rotations. Let's take an example to understand how we can use the builtin method to perform the right Rotation. RightRotationExample2.java Output: Left Rotation of the ListWe can implement rotation in a Java program with/without using builtin methods. Let's understand both of the ways one by one: Left Rotation Without using a builtin MethodLeft Rotation is done by shifting elements to the left side of the list. We use the following steps to perform the right Rotation in a list:
Let's implement the code for the above theory to perform left rotation without using the builtin method: LeftRotationExample1.java Output: Left Rotation by Using a builtin MethodJust like right Rotation, we also use the rotate() method of the Collections class to perform left Rotation. The only change between right and left rotation is that in the right Rotation, the value of the distance parameter is positive, whereas, in the left Rotation, its value is negative. Let's take an example to understand how we can use the builtin method to perform left Rotation. LeftRotationExample2.java Output:
Next TopicCount of Range Sum Problem in Java
