Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

ArrayList Sort in Java

Last Updated on September 22, 2023 by Mayank Dham

In Java, the ArrayList class offers dynamic and efficient storage for collections of objects. However, mere storage is often insufficient; ordering the elements within the ArrayList becomes equally important. This is where the array list sort in Java comes into play. Java provides a convenient sorting mechanism through which ArrayList elements can be arranged in a desired order, enhancing the efficiency of search, retrieval, and manipulation operations. Understanding how to utilize the ArrayList’s sorting functionality is key to optimizing data processing in various Java applications. This discussion delves into the intricacies of sorting ArrayLists in Java, exploring the mechanisms, advantages, and considerations that come into play when arranging elements within this versatile collection.

What is Collection?

Collection is a framework in java that composes of interfaces and classes that can be used for the storage of objects. Here is an illustration that can help identify the containers that can be used for the respective storage capabilities.

Reasons to use ArrayList

ArrayList is used for obviously better reasons such as they offer more flexibility, the reason being that they are stored dynamically and have no size limit, unlike statics arrays that need to be given a fixed space to hold the elements upon allocation.

It inherits the Abstract List Class that guarantees it to obtain the features and properties of List on top of its own.
To use ArrayList, which can be imported from java.util package making us implement the class from the collection framework.

ArrayList Sort in Java

ArrayList Sort in Java can be performed to sort the ArrayList in ascending or descending order with a condition that there are no elements of different types such that all of them are mutually comparable to each other. As soon as it encounters a different element, it throws up a ClassCastException

Arr1 = [ “PrepBytes”,”CPP”,”Java”]
Arr2 =  [ “PrepBytes”,1,”Java”]

For example. ArrayList sort can be performed on Arr1 to sort in lexicographic order while Arr2 will fail to do so as it has an integer sandwiched between strings at index 0 and index 2.

To sort the ArrayList in ascending order, we use the sort() method of the collection class. It needs the ArrayList to be passed as a parameter and returns a sorted ArrayList.

Sorting the ArrayList in descending order can be done by giving an extra parameter to the sort method. reverseOrder() method is passed along with the ArrayList as a parameter to get an ArrayList that is sorted in reversed order, numerically, or lexicographically.

Program to Implement ArrayList Sort

Now that we have seen the concept and all the pre-requisite for ArrayList, below is the code to sort an ArrayList using both the methods discussed above.

To Sort in Ascending Order:

import java.util.*;    
public class Main 
{
  
public static void main (String[]args)
  {
    ArrayList < String > list = new ArrayList < String > ();
    list.add ("Apple");
    list.add ("Orange");
    list.add ("Cherry");
    list.add ("Apricot");


    System.out.println ("Before: " + list);
    Collections.sort (list);
    System.out.println ("After: " + list);
   } 
}

Output:

Before: [Apple, Orange, Cherry, Apricot]
After: [Apple, Apricot, Cherry, Orange]

Explanation:
In the above code, an object of the ArrayList class is created and multiple strings are appended into the ArrayList using the add() method. Later, the ArrayList is printed before being sorted, with the sort() operation performed and giving us the output ArrayList in lexicographically ascending order.

To Sort in Descending Order:

import java.util.*;    
public class Main 
{
  
public static void main (String[]args)
  {
    ArrayList < String > list = new ArrayList < String > ();
    list.add ("Apple");
    list.add ("Orange");
    list.add ("Cherry");
    list.add ("Apricot");


    System.out.println ("Before: " + list);
    Collections.sort (list, Collections.reverseOrder());
    System.out.println ("After: " + list);
   } 
}

Output:

Before: [Apple, Orange, Cherry, Apricot]
After: [Orange, Cherry, Apricot, Apple]

Explanation:
In the above code, an object of the ArrayList class is created and multiple strings are appended into the ArrayList using the add() method. Later, the ArrayList is printed before being sorted, with the sort() operation performed, with reverseOrder() passed as the second parameter and giving us the output ArrayList in lexicographically descending order.

A similar operation can be performed on integers to sort the array in ascending and descending order with the same logic as discussed above, The code for both can be found as follows:-

Ascending Order for Integers:

import java.util.*;    
public class Main
{
  
public static void main (String[]args)
  {
    ArrayList < Integer > list = new ArrayList < Integer > ();
    list.add (4);
    list.add (96);
    list.add (-13);
    list.add (5);


    System.out.println ("Before: " + list);
    Collections.sort (list);
    System.out.println ("After: " + list);
   } 
}

Output:

Before: [4, 96, -13, 5]
After: [-13, 4, 5, 96]

Descending Order for Integers:

import java.util.*;    
public class Main
{
  
public static void main (String[]args)
  {
    ArrayList < Integer > list = new ArrayList < Integer > ();
    list.add (4);
    list.add (96);
    list.add (-13);
    list.add (5);


    System.out.println ("Before: " + list);
    Collections.sort (list,Collections.reverseOrder());
    System.out.println ("After: " + list);
   } 
}

Output:

Before: [4, 96, -13, 5]
After: [96, 5, 4, -13]

Analysis of ArrayList Sort in Java

The time complexity of ArrayList tends to be O(nlogn) while the Space Complexity remains O(1) as there is no extra space being used in performing ArrayList Sort.

Conclusion
In this article, we discussed what are collections and how ArrayLists can be used to store the elements, later we moved to the foci of the article which is ArrayList Sort, we studied the variants of it and implemented a program to sort in ascending as well as descending order for string and numerical inputs.

We hope you liked this article on ArrayList Sort and expect to see you again at PrepBytes Blog with another insightful piece of article.

Frequently Asked Questions

1. What method is used to sort the ArrayList in reversed order?
Collections.reverseOrder() is passed as a parameter in the sort() method to return an ArrayList sorted in descending order.

2. What is the time complexity of collections.sort() ?
Time Complexity of collections.sort() is O(nlogn) in the worst case.

3. What is mutually comparable in ArrayList Sort?
Mutually Comparable states that all the elements must be of the same type in order to be sorted else ClassCastException is encountered.

Q4. Can I sort an ArrayList of custom objects?
Yes, you can sort an ArrayList containing custom objects by either implementing the Comparable interface in the custom class to define the natural ordering, or by providing a custom comparator using the Collections.sort() method.

Q5. What are the performance considerations when sorting large ArrayLists?
Sorting large ArrayLists can have performance implications, especially with custom comparators that involve complex comparison logic. It’s important to be aware of the time complexity of the sorting algorithm and consider using more efficient algorithms, such as merge sort, which is used internally by Collections.sort().

Leave a Reply

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