Different Approaches To Sorting Elements of an ArrayList in Java

Like this post? Rate it:
2698

One of the most commonly used collection classes of Java Collection Framework is ArrayList. This object has the ability to store a group of other objects and allow us to manipulate those objects one by one because of the flexibility it provides. ArrayList is an implementation of List that implements a dynamic array to store elements internally. This means that ArrayList can shrink and grow as you remove and add new elements to and from it. For example we could use ArrayList to store all the String names of burger toppings offered by a particular restaurant, or alternatively, we could store or bookmark all the favorite URL’s of individual user.

Let us look into an example as to how ArrayList actually works and then we will discuss most important operation on ArrayList that usually required mostly during the implementation of enterprise level application, i.e. to sort elements of an ArrayList with different approaches.

Java ArrayList – A short version

As we discussed, ArrayList is just an object, so we will create it simple like any other object, calling ‘new’ and storing a pointer into this object. When created, initially it will be empty, it does not contain any objects. Traditionally, we call those things stored inside of a collection as ‘elements’. In Java, collections always store pointer to objects, so we can use the words pointer or object in order to refer to those elements in a collection.

Let’s have a look at the code.

In this way, we create a new ArrayList which is initially empty.

We added three strings to the ArrayList. To add any object in the ArrayList, we call the add method by passing a pointer to the object which we want to store. The above piece of code added pointers to String objects.

Index Numbers

The question is that how can we identify each of the three elements? The ArrayList once created, gives each element an index number for identification. The first element is considered as number 0, the next is number 1, and the sequence continues. Index number helps us identify individual elements so we can manipulate them. This indexing is common in programming and it is worth getting accustomed to this.

To look into elements individually ArrayList has two methods to do that. The size () method, which returns the int current number of elements and get () method, which takes an int index argument and return the pointer at the index number.

Simply put, with the size () method you can see how many elements are there, and with the get () method you can get any particular elements w.r.t its index.

Now let’s move to the actual topic to get familiar with the approaches that sort elements of an ArrayList.

Sort an Array

Consider an Array that sorts the list of soft drinks as String objects. To sort an Array, we simply use Array.sort () method by passing the object populated with the names of soft drinks.

Code:

Output:

Sort an ArrayList

Consider an ArrayList that sorts the list of soft drinks as String objects. To sort an ArrayList, we simply use Collection.sort () method by passing the object populated with the names of soft drinks.

Code:

Output:

It seems that sorting elements of an ArrayList is quite simple. We simply need to call Collection.sort () method passing the object to the ArrayList whose elements needs to be sorted. As you move forward and experience advance and complex scenarios you need to do more than those easy steps.

Sort an Object with Comparable

Let us now create a Soft Drinks class.

To sort the above code, you may think of Array.sort () method, see below:

By doing so you will get an error because in the above code you haven’t even mentioned what to sort.

To resolve the error and sort the object properly, you need to make an object implement the Comparable interface and override it with compareTo() method. See below:

The new class implemented the Comparable interface by overriding compareTo() method to compare quantity in ascending order. Run the code and see the output.

Soft Drinks Array is now sorted in ascending order quantity wise.

Sort an Object with Comparator

What if the scenario required you to sort out with multiple properties such as drinkName or Quanitity? While the Comparable only allows you to sort with a single property, Comparator gives us an advantage to sort with multiple properties. See the code below:

The softDrinks class contains a Comparator method and it compares the drinkName. Now you can sort the softDrinks object based on both ‘quantity’ and ‘drinkName’.

Sort on the basis of ‘drinkName’ in ascending order

Output:

Sort on the basis of ‘quantity’ in ascending order

Output:

Comparable vs Comparator

  1. Comparator interface is defined in java.util.package, whereas Comparable interface is defined in java.lang.package.
  2. Comparator interface contains two methods: compare () and equals(). While Comparable contains only one method: compareTo().
  3. Comparator is used for customized sorting, whereas Comparable used for natural default sorting order.
  4. In case of Comparator we do not need to make any change in the class, whereas in Comparable we need to implement a class to use it.

Java ArrayList Sorting Methods: Conclusion

In the above post we discussed in details different approaches of sorting elements in ArrayList with primary focus on using Comparable and the other one is Comparator. These approaches also make confusion much of the time for developers, as they are unable to decide which one to opt. Just keep in mind a simple rule of thumb:

Comparator: When compare two different objects.

Comparable: When compare one object with another object.

You can choose any interface depends on the functionality you tend to achieve. One cannot give verdicts whether one interface is better than the other one.

Happy Learning!

No comments yet. Be the first to add a comment!

Write a comment

Loading...