Java Program to Traverse Through ArrayList in Reverse Direction
Last Updated :
19 Jul, 2022
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. The task is to insert an element in ArrayList and then Reverse it or say reverse the direction.
Example :
Input : 1, 2, 3, 4, 5, 6
Output : 6, 5, 4, 3, 2, 1
Input : 10, 22, 34, 3, 2, 6
Output : 6, 2, 3, 34, 22, 10
Input : 11, 22, 34, 42, 51 , 63
Output : 63, 51, 42, 34, 22, 11
There are several methods by which we can Iterate and print List in reverse direction listed below.
Method 1: (Using ListIterator)
1. Declare an ArrayList
// size of n
ArrayList<Integer> List = new ArrayList<Integer>(n);
2. By using the add function we push the element into the ArrayList.
3. After reaching the last element of ArrayList traverse by using iterator. hasPrevious() method returns true if an element is present at the back of the current element, traverse until hasPrevious( ) return false.
4. While traversing print the current element of ArrayList.
Java
// Traverse through ArrayList in
// reverse direction using List
// Iterator in Java
import java.util.ListIterator;
import java.io.*;
import java.util.ArrayList;
class GFG {
public static void main(String[] args)
{
// create an instance of arraylist
ArrayList<Integer> List = new ArrayList<Integer>();
// add elements
List.add(10);
List.add(9);
List.add(8);
List.add(7);
List.add(6);
// create a listiterator on list
ListIterator<Integer> List_Iterator
= List.listIterator(List.size());
System.out.println("Reversed : ");
// print ArrayList in reverse direction using
// listiterator
while (List_Iterator.hasPrevious()) {
System.out.println(List_Iterator.previous());
}
}
}
OutputReversed :
6
7
8
9
10
Time Complexity: O(n)
Auxiliary Space: O(n) where n is size of List
Method 2: (Using Stream)
The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result.
- Get Stream using List.stream().
- Collect elements of this stream to a LinkedList using Stream.collect().
- Iterate through the LinkedList in reverse sequential order using LinkedList.descendingIterator() method.
- Perform the print operation on each element of the ArrayList using forEachRemaining(). We can provide the method reference System.out::println Iterator to the forEachRemaining().
Java
// Traverse through ArrayList in
// reverse direction Using
// stream in Java
import java.lang.*;
import java.util.stream.*;
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// create a list
List<Integer> Arlist = Arrays.asList(5, 2, 4, 8);
System.out.println("Reversed : ");
// create a stream
// collect the elements after these operations
// create a descending iterator on the stream
// loop through the descending iterator
// print the element
Arlist.stream()
.collect(
Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(System.out::println);
}
}
Time Complexity: O(n)
Auxiliary Space: O(n) where n is size of List
Method 3: (Using For Loop) We know that List is an ordered collection, and we can access the element of the list just by its index, so Define an ArrayList and iterate from last using a for loop till the first element and print each element.
Java
// Traverse through ArrayList in
// reverse direction using For
// Loop in Java
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// create a list
List<Integer> Arlist = Arrays.asList(5, 4, 8, 2);
System.out.println("Reversed :");
// Printing in reverse
for (int i = Arlist.size() - 1; i >= 0; i--) {
System.out.println(Arlist.get(i));
}
}
}
Time Complexity: O(n)
Auxiliary Space: O(n) where n is size of List
Method 4: (Using Apache Common’s ReverseListIterator)
This method provides ReverseListIterator that we can use to iterate List in reverse order. As we use the ReverseListIterator then next() will return the last element from the array list, Then as we call the next element then next bracket will return the previous element of the current element, and has next will check whether our ArrayList contains an element or not.
Java
// Traverse through ArrayList in reverse direction using
// ReverseListIterator in Java
import org.apache.commons.collections.iterators.ReverseListIterator;
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args)
{
// create a list
List<Integer> list = Arrays.asList(1, 5, 8, 7);
// create a reverse listiterator
ReverseListIterator it
= new ReverseListIterator(list);
System.out.println("Reversed : ");
// print the elements
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Output
Reversed :
7
8
5
1
Time Complexity: O(n)
Auxiliary Space: O(n) where n is size of List
Similar Reads
Traverse Through ArrayList in Forward Direction in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in a proper organized sequence). ArrayList can be
3 min read
Convert ArrayList to Vector in Java
There are several ways to convert ArrayList to Vector. We can use a vector constructor for converting ArrayList to vector. We can read ArrayList elements one by one and add them in vector. Approach 1: (Using Vector Constructor) Create an ArrayList.Add elements in ArrayList.Create a vector and pass t
3 min read
How to Convert TreeMap to an ArrayList in Java?
TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot
4 min read
Java Program to Create ArrayList From Enumeration
Enumerations serve the purpose of representing a group of named constants in a programming language. Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay
2 min read
Java Program to Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples:Â Â Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7
2 min read
Java Program to Sort ArrayList of Custom Objects By Property
Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares t
2 min read
How to Iterate the Vector Elements in the Reverse Order in Java?
The Vector class is found in java.util package and it implements List interface. The Vector class is included in the java collection framework from Java version 1.2. Unlike arrays, vectors can grow and shrink their size, and thus they are also called the Dynamic Array. Vectors are synchronized, ie t
3 min read
Java Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example : Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Algorithm : rotate(arr[], d, n) reverse(arr[], 1, d) ; reverse(arr[], d + 1, n
3 min read
Java Program to Remove a Specific Element From a Collection
remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index fr
3 min read
Java Program for Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n
2 min read