How to sort ArrayList in Java

Read Time:8 Minute, 57 Second

Table of Contents

The collection is a Java framework that provides interfaces (Set, List, Queue, and so on) and classes (ArrayList, LinkedList, and so on) for storing a collection of objects. These classes keep data in random order. Sorting is a term used to describe the process of arranging data in an orderly fashion. You can do sorting in two ways: ascending or descending order.

This section will explore how to sort an ArrayList in ascending and descending order.


ArrayList is a Collections framework class in Java, defined in the Java.util package. It is a descendant of the AbstractList class. Further, it keeps track of the elements in real-time. ArrayList has the advantage of having no size limit. It is more adaptable than a standard array. Also, it may contain duplicate items. Because it implements the List interface, we can utilize all of the List interface’s methods. An ArrayList can be sorted in two ways: ascending and descending. In Java, the Collections class has two methods for sorting an ArrayList.

  • sort()
  • reverseOrder()

Collections.sort() as a method for sorting data in a collection

The sort() function of the Collections class in Java is used to sort an ArrayList. It takes an ArrayList object as an argument and returns an ArrayList that has been sorted in ascending order according to the natural ordering of its elements.

The syntax is as follows:


Remember that all elements in the ArrayList must be comparable to each other. Else the ClassCastException will be thrown. Mutually similar means that the elements in the list must be of the same type. Take, for example, the following code snippet:

In the example above, a list comprises four members, three of which are of the String type and one of which is the Integer type. The String’s three elements are interchangeable, but the Integer’s element is not. As a result, the elements in the list must all be of the same type.

Collections.reverseOrder() as a method that reverses the order of items in a collection

You can use the reverseOrder() method of the Java Collections class to sort an ArrayList in descending order. It allows us to reverse-lexicographically sort the ArrayList. The Syntax of .reverseOrder() is as follows:

It returns a comparator that reorders a collection of objects that implement the Comparable interface in the opposite direction of their natural ordering. It’s important to remember that we don’t call the reverseOrder() method directly. As shown below, we utilize it in conjunction with the collection.sort() method.

As a result, sorting an ArrayList in descending order is accomplished in two steps: first, the ArrayList sorts the data in ascending order, and then the reverseOrder() method reverses the sorted data. Let’s write some programs to sort the ArrayList in ascending order.


ArrayList sorted in ascending order

We’ve generated an ArrayList of type String and added some members to it in the following example. Then we passed the object of the ArrayList class, which is a list that sorts the elements in ascending order, to the sort() method of the Collections class.

Example 1: SortArrayList

Example 2: SortArrayList

ArrayList sorted in descending order

We’ve generated an ArrayList of type String and added some members to it in the following example. Then we passed the object of the ArrayList class, which is a list that sorts the elements in descending order, to the reverseOrder() and sort() methods of the Collections class.

Example: SortArrayList

Example: SortArrayList

Example: Sort an ArrayList in ascending order

The task is to sort an ArrayList in ascending order in Java, given an unsorted ArrayList. The sort() function of the Collections Class in Java is used to sort an ArrayList. This sort() function accepts a collection as an argument and produces a collection sorted by default in ascending order.

Example: ArrayList Sorting in Natural Order

In the previous example, we used the sort() method to sort the ArrayList named languages. Take note of the line,


The Java Comparator Interface’s naturalOrder() function indicates that elements are sorted in natural order (i.e., ascending order). In addition, the Comparator interface has a method for sorting components in descending order. As an example,

The Comparator interface’s reverseOrder() function indicates that elements are sorted in reverse order (i.e., descending order). The Collections.sort() method is the more convenient option for sorting an ArrayList.

Using Comparables to Sort an ArrayList

The single important method in the Comparable interface is the compareTo() method. A Comparable-implemented object can compare itself to another Comparable-implemented object of the same type. The compareTo() method in the Ccmparable class has to be overridden.

This method takes an object of the same type as compareTo() and implements the logic for comparing it to the one passed in. The compareTo() method returns the comparison result as an integer. This object is greater than the object supplied to compareTo() if the value is positive. This object is less than the object supplied to compareTo() with a negative value. The number zero denotes equality between the two things.

Let’s look at a CodingStudent class with objects that we want to store in an ArrayList and then sort. The CodingStudent class includes three fields: a String name and gender and an integer age. We want to use the age attribute to sort the CodingStudent objects in the ArrayList. We’ll need to implement Comparable in the CodingStudent class and override the compareTo() method.


This is the CodingStudent class’s code.

We built the comparison logic based on the age field in the override compareTo() method of the CodingStudent class above. Many programmers, in our experience, have reverted to the old method of returning the comparison result as:

Although utilizing this return statement may appear tempting and will have no effect on our example, we recommend that you avoid it. Consider the outcome of comparing integer values in which one or both are negative.

It might cause faults in your application that cause it to behave unpredictably, and because such bugs are subtle, they are tough to spot, especially in large business systems. Then, we’ll develop a helper class that sorts ArrayList objects containing CodingStudent elements for clients.

We initialized an ArrayList object in the CodingStudentSorter class, which the client will give through the constructor when instantiating CodingStudentSorter. The getSortedCodingStudentByAge() method was then created. We passed the initialized ArrayList to Collections.sort() in this method. Finally, it returns the sorted ArrayList. After that, we’ll create a test class to put our code to the test.


We created four CodingStudent objects and added them to an ArrayList in the test class above. We then passed our ArrayList to the constructor of the CodingStudentSorter class. Finally, we invoked CodingStudentSorter’s getSortedJobCandidateByAge() method and printed the sorted ArrayList that the method returned.

Comparable is a typical method for sorting an ArrayList. However, you must be aware of some limitations. You must implement Comparable and override the compareTo() function in the class whose object you want to sort. It effectively means that you can only compare items based on one field (age in our example). What if your requirements specify that you must be able to sort CodingStudent objects by both name and age? Comparable isn’t the answer.

Furthermore, because comparison logic is part of the class whose objects must be compared, there is no way for the comparison logic to be reused. Java provides the Comparator interface in the Java.util package to satisfy such sorting comparison requirements.

Using a comparator to sort an ArrayList

The Comparator interface has only one comparison method called compare() like the Comparable interface. The compare() method, unlike the compareTo() method of Comparable, compares two separate objects of the same type.

The comparator will be used to rank items of the same CodingStudent class as before, but with a few variations. By creating Comparatoras anonymous inner classes, we will be able to sort CodingStudent objects by name and age.


The code for the CodingStudent class using comparator is shown below.

From Line 29 to Line 35 of the above class, we created an anonymous class and implemented the compare()method, which allows us to rank the CodingStudent objects by age in descending order.

We created another anonymous class and implemented the compare() method from Line 37 to Line 42, which allows us to rank CodingStudent objects by name in ascending order. We’ll now create a class that sorts the ArrayList’s elements for clients.

The getSortedCodingStudentByAge() method was written in the previous class. We used the overloaded form of Collections in this method. sort() takes two arguments: an ArrayList object to sort and a Comparator object to compare age. We used the overloaded version of Collections again in the getSortedCodingStudentByName() method. sort() returns an ArrayList object sorted and a Comparator object used to compare names. Let’s create a test class to put our code to the test.

In the JUnit setup() method annotated with @Before, we populated CodingStudent objects in an ArrayList and generated a CodingStudentSorter object in the test class.


We invoked the getSortedCodingStudentByAge() method in the testGetSortedCodingStudentByAge() method and wrote out the sorted ArrayList that the function returns in thetestGetSortedCodingStudentByAge() method. The getSortedCodingStudentByName() function was called in the testGetSortedCodingStudentByName() test method, and the sorted ArrayList returned by the method was written out.


Because of its functionality and versatility, ArrayList is one of the most often used collection classes in the Java Collection Framework. ArrayList is a List implementation that uses a dynamic array to store elements internally. As a result, as you add and delete elements from an ArrayList, it can dynamically grow and decrease.

We’ve gone through one of the essential ArrayList operations that you’ll almost certainly need to use during corporate application development. It’s sorting an ArrayList’s elements.

We looked at various methods for sorting ArrayList members. One employs Comparable, whereas the other employs comparator. For programmers, the approach to choosing has always been a source of consternation. Essentially, a Comparable object can say, “I can compare myself to another object,” whereas a Comparator object can say, “I can compare two different objects.” It’s impossible to say that one interface is superior to the other. The interface you select is determined by the capabilities you require.


Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
How to run grep in Python Previous post How to run grep in Python
Best Crypto Trading Bots for 2022: Here Are Our Top Picks Next post Best Crypto Trading Bots for 2022: Here Are Our Top Picks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.