How To Reverse An ArrayList In Java?
In this post, we will see how to reverse an ArrayList in Java by creating a copy of it. In reverse order without altering the ordering of elements in the original list. ArrayList is nothing but a dynamic array, which can resize itself.
- 1 What is Collections Class
- 2 How Collections Reverse Work
- 3 Example
- 4 Conclusion
- 5 Some Useful Methods Of java Util Collections
What is Collections Class
The specified list may or may not be mutable, but the returned list should be mutable. The Collections class provides a method named reverse() this method accepts a list and reverses the order of elements in it.
- Recyclerview with card view android example
- Top 10 free WordPress plugins for bloggers
- Convert multidimensional array to XML file in PHP
How Collections Reverse Work
The given ArrayList can be reversed using Collections.reverse() method. Collections is a class in java util package which contains various static methods for searching, sorting, reversing, finding min, max….etc.
public class ReverseArrayList
public static void main(String args)
ArrayList<String> list = new ArrayList<String>();
//Printing list before reverse
System.out.println("ArrayList Before Reverse :");
//Reversing the list using Collections.reverse() method
//Printing list after reverse
System.out.println("ArrayList After Reverse :");
There are many types of exercise you can do regularly. Above all code is fit for this example. In conclusion, you can see the output of the above code for reverse an ArrayList in Java :
ArrayList Before Reverse :
[Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Cream Sandwich, Jelly Bean]
ArrayList After Reverse :
[Jelly Bean, Cream Sandwich, Honeycomb, Gingerbread, Froyo, Eclair, Donut, Cupcake ]
Some Useful Methods Of java Util Collections
Collections.copy(): This method is used to copy all elements from one list to another list.
Collections replace All
Collections.replaceAll(): In addition, It replaces all occurrences of old value with new value in the given list.
Collections synchronized List
Collections.synchronizedList(): Above method returns the synchronized i.e thread-safe list backed by the specified list.
Collections synchronized Collection
Collections.synchronizedCollection(): This method returns the synchronized version of the specified Collection.
Collections.max(): Collections max returns the maximum element in the given Collection.
Collections.min(): Similarly, It returns the minimum element in the given Collection.