Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
CopyOnWriteArrayList listIterator() method in Java
Next article icon

Reverse an ArrayList in Java using ListIterator

Last Updated : 18 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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());
      }
         
    }
}
 
 
Output
Before reverse[2, 5, 7] 7 5 2 


Next Article
CopyOnWriteArrayList listIterator() method in Java

S

SujanM
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

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 e
    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 Va
    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 commo
    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(Descend
    5 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences