Java arraylist reverse: In the previous article, we have seen Java Program to Compare Two ArrayList in Java
In this article we are going to see how we can reverse ArrayList in Java.
Java Program to Reverse ArrayList in Java
How to reverse arraylist in java: Before jumping to the program directly, first let’s know how we can reverse an arraylist.
In Java Collection class we have inbuilt reverse()
method can be used to reverse any collection directly.
Syntax: Collections.reverse(arrayList_Name)
Where,
arrayList_Name
refers to the ArrayList.
Let’s see the program to understand it more clearly.
Java Program to Reverse ArrayList in Java By Using Collections.reverse( ) Method
Approach:
- Create an arraylist and add some elements to it
- Display the elements.
- Use the
reverse()
method of collection method and pass the arraylist into it. - Display the modified list.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Creating an empty ArrayList ArrayList<String> arr = new ArrayList<String>(); // Adding elements to the arrayList arr.add("One"); arr.add("Two"); arr.add("Three"); // Displaying the list System.out.println("Arraylist 1 before reversing "+arr); //Reversing ArrayList using the reverse() Collections.reverse(arr); // Printing the modified arraylist System.out.println("After Reversal "+arr); } }
Output: Arraylist 1 before reversing [One, Two, Three] After Reversal [Three, Two, One]
Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.
Related Java Programs: