Java Program to Traverse Through ArrayList in Reverse Direction
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.
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.
Reversed : 6 7 8 9 10
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().
Reversed : 8 4 2 5
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.
Reversed : 2 8 4 5
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.
Reversed : 7 8 5 1
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.