Skip to content
Related Articles

Related Articles

Java Program to Traverse Through ArrayList in Reverse Direction
  • Last Updated : 22 Dec, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());
        }
    }
}

chevron_right


Output

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().

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output

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. 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
        }
    }
}

chevron_right


Output

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.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());
        }
    }
}

chevron_right


Output 

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :