Reverse an ArrayList in Java using ListIterator
Last Updated :
18 May, 2023
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:
1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an arraylist as a parameter, traverses in reverse order and adds all the elements to the newly created arraylist. Finally the reversed arraylist is returned.
Java
// Java program for reversing an arraylist
import java.io.*;
import java.util.*;
class RevArrayList {
// Takes an arraylist as a parameter and returns
// a reversed arraylist
public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist)
{
// Arraylist for storing reversed elements
ArrayList<Integer> revArrayList = new ArrayList<Integer>();
for (int i = alist.size() - 1; i >= 0; i--) {
// Append the elements in reverse order
revArrayList.add(alist.get(i));
}
// Return the reversed arraylist
return revArrayList;
}
// Iterate through all the elements and print
public void printElements(ArrayList<Integer> alist)
{
for (int i = 0; i < alist.size(); i++) {
System.out.print(alist.get(i) + " ");
}
}
}
public class GFG {
public static void main(String[] args)
{
RevArrayList obj = new RevArrayList();
// Declaring arraylist without any initial size
ArrayList<Integer> arrayli = new ArrayList<Integer>();
// Appending elements at the end of the list
arrayli.add(new Integer(1));
arrayli.add(new Integer(2));
arrayli.add(new Integer(3));
arrayli.add(new Integer(4));
System.out.print("Elements before reversing:");
obj.printElements(arrayli);
arrayli = obj.reverseArrayList(arrayli);
System.out.print("\nElements after reversing:");
obj.printElements(arrayli);
}
}
Output: Elements before reversing:1 2 3 4
Elements after reversing:4 3 2 1
1. By writing our own function(without using additional space): In the previous example, an arraylist is used additionally for storing all the reversed elements which takes more space. To avoid that, same arraylist can be used for reversing.
Logic:
1. Run the loop for n/2 times where 'n' is the number of elements in the arraylist.
2. In the first pass, Swap the first and nth element
3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the arraylist.
4. Return the arraylist after the loop termination.
Java
// Java program for reversing an arraylist
import java.io.*;
import java.util.*;
class RevArrayList {
// Takes an arraylist as a parameter and returns
// a reversed arraylist
public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist)
{
// Arraylist for storing reversed elements
// this.revArrayList = alist;
for (int i = 0; i < alist.size() / 2; i++) {
Integer temp = alist.get(i);
alist.set(i, alist.get(alist.size() - i - 1));
alist.set(alist.size() - i - 1, temp);
}
// Return the reversed arraylist
return alist;
}
// Iterate through all the elements and print
public void printElements(ArrayList<Integer> alist)
{
for (int i = 0; i < alist.size(); i++) {
System.out.print(alist.get(i) + " ");
}
}
}
public class GFG1 {
public static void main(String[] args)
{
RevArrayList obj = new RevArrayList();
// Declaring arraylist without any initial size
ArrayList<Integer> arrayli = new ArrayList<Integer>();
// Appending elements at the end of the list
arrayli.add(new Integer(12));
arrayli.add(new Integer(13));
arrayli.add(new Integer(123));
arrayli.add(new Integer(54));
arrayli.add(new Integer(1));
System.out.print("Elements before reversing: ");
obj.printElements(arrayli);
arrayli = obj.reverseArrayList(arrayli);
System.out.print("\nElements after reversing: ");
obj.printElements(arrayli);
}
}
Output: Elements before reversing: 12 13 123 54 1
Elements after reversing: 1 54 123 13 12
2. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min....etc. We can make use of the In-built Collections.reverse() method for reversing an arraylist. It takes a list as an input parameter and returns the reversed list.
Java
// Java program for reversing an arraylist
import java.io.*;
import java.util.*;
public class GFG2 {
public static void main(String[] args)
{
// Declaring arraylist without any initial size
ArrayList<Integer> arrayli = new ArrayList<Integer>();
// Appending elements at the end of the list
arrayli.add(new Integer(9));
arrayli.add(new Integer(145));
arrayli.add(new Integer(878));
arrayli.add(new Integer(343));
arrayli.add(new Integer(5));
System.out.print("Elements before reversing: ");
printElements(arrayli);
// Collections.reverse method takes a list as a
// parameter and reverses the passed parameter
//(no new array list is required)
Collections.reverse(arrayli);
System.out.print("\nElements after reversing: ");
printElements(arrayli);
}
// Iterate through all the elements and print
public static void printElements(ArrayList<Integer> alist)
{
for (int i = 0; i < alist.size(); i++) {
System.out.print(alist.get(i) + " ");
}
}
}
Output: Elements before reversing: 9 145 878 343 5
Elements after reversing: 5 343 878 145 9
3. Reversing an arraylist of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An arraylist is created that takes only Employee(user defined) Objects. These objects are added to the arraylist using add() method. The arraylist is reversed using In-built reverse() method of Collections class.
The printElements() static method is used only to avoid writing one more class in the program.
Java
// Java program for reversing an arraylist
import java.io.*;
import java.util.*;
class Employee {
int empID;
String empName;
String deptName;
// Constructor for initializing the class variables
public Employee(int empID, String empName, String deptName)
{
this.empID = empID;
this.empName = empName;
this.deptName = deptName;
}
}
public class GFG3 {
public static void main(String[] args)
{
// Declaring arraylist without any initial size
ArrayList<Employee> arrayli = new ArrayList<Employee>();
// Creating user defined objects
Employee emp1 = new Employee(123, "Rama", "Facilities");
Employee emp2 = new Employee(124, "Lakshman", "Transport");
Employee emp3 = new Employee(125, "Ravan", "Packing");
// Appending all the objects for arraylist
arrayli.add(emp1);
arrayli.add(emp2);
arrayli.add(emp3);
System.out.print("Elements before reversing: ");
printElements(arrayli);
// Collections.reverse method takes a list as a
// parameter and reverse the list
Collections.reverse(arrayli);
System.out.print("\nElements after reversing: ");
printElements(arrayli);
}
// Iterate through all the elements and print
public static void printElements(ArrayList<Employee> alist)
{
for (int i = 0; i < alist.size(); i++) {
System.out.print("\n EmpID:" + alist.get(i).empID +
", EmpName:" + alist.get(i).empName + ", Department:" +
alist.get(i).deptName);
}
}
}
Output: Elements before reversing:
EmpID:123, EmpName:Rama, Department:Facilities
EmpID:124, EmpName:Lakshman, Department:Transport
EmpID:125, EmpName:Ravan, Department:Packing
Elements after reversing:
EmpID:125, EmpName:Ravan, Department:Packing
EmpID:124, EmpName:Lakshman, Department:Transport
EmpID:123, EmpName:Rama, Department:Facilities
Using ListIterator:
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(2);
list.add(5);
list.add(7);
System.out.println("Before reverse" + list);
/*You could use the method listIterator(int index).
It allows you to place the iterator at the position defined by index.
*/
ListIterator iterator=list.listIterator(list.size());
while(iterator.hasPrevious())
{
System.out.println(iterator.previous());
}
}
}
OutputBefore reverse[2, 5, 7]
7
5
2
Similar Reads
ArrayList listIterator() Method in Java
The listIterator() method of ArrayList class in Java is used to return a ListIterator for traversing the elements of the list in proper sequence. The iterator allows both forward and backward traversal of the list.Example 1: Here, we use the listIterator() method to obtain a ListIterator over all el
3 min read
CopyOnWriteArrayList listIterator() method in Java
The listIterator() method of CopyOnWriteArrayList returns an listIterator over the elements in this list in proper sequence. The listIterator does NOT support the remove, set or add methods. Syntax:Â public ListIterator listIterator() Parameters: The function does not accept any parameters. Return V
3 min read
Reverse an Array in Java
Reversing an Array is a common task in every programming language. In Java, there are multiple ways to reverse an array. We can reverse it manually or by using built-in Java methods. In this article, we will discuss different methods to reverse an array with examples.Let us first see the most common
4 min read
Vector listIterator() method in Java with Examples
java.util.Vector.listIterator() This method returns a list iterator over the elements of a Vector object in proper sequence. It is bidirectional, so both forward and backward traversal is possible, using next() and previous() respectively. The iterator thus returned is fail-fast. This means that str
3 min read
ArrayList and LinkedList remove() methods in Java with Examples
List interface in Java (which is implemented by ArrayList and LinkedList) provides two versions of remove method. boolean remove(Object obj) : It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present. Removes t
3 min read
Enumeration vs Iterator vs ListIterator in Java
Enumeration is an interface. It is used in the collection framework in java to retrieve the elements one by one. Enumeration is a legacy interface that is applicable only for legacy classes like Vector, HashTable, Stack, etc. It provides a single direction iteration. By using enumeration, we can per
4 min read
Sort an Array in Java using Comparator
A Comparator is an object that can be used to compare two objects and determine their order. We can use a Comparator to sort a list of objects in any order we can choose, not just in ascending order.Examples:Array(Ascending Order): Input: arr = (4, 2, 5, 1, 3) Output: [1, 2, 3, 4, 5] Array(Descendin
4 min read
AbstractList listIterator() Method in Java with Examples
The listIterator() method of java.util.AbstractList class is used to return a list-iterator containing the same elements as that of the AbstractList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method. Syntax: ListIterator new_l
2 min read
When to use Queue over ArrayList in Java?
Array List:ArrayList is a part of the Collection Framework and implements the java List Interface. This class provides the methods to resize the list based on needs.It allows having null and duplicate values.The Array List is similar to a vector in java except that it is unsynchronized. It is not th
6 min read
Arraylist removeRange() Method in Java with Examples
The removeRange() method of the ArrayList class in Java is used to remove all elements from the list within the specified range of indices. This method removes the elements from the starting index (fromIndex) to the ending index (toIndex). Example 1: Here, we use the removeRange() method to remove a
3 min read