How to Sort ArrayList in Java

In Java, Collection is a framework that provides interfaces (Set, List, Queue, etc.) and classes (ArrayList, LinkedList, etc.) to store the group of objects. These classes store data in an unordered manner. Sometimes we need to arrange data in an ordered manner which is known as sorting. The sorting can be performed in two ways either in ascending or descending order.

In this section, we will learn how to sort ArrayList in ascending and descending order.

ArrayList

In Java, ArrayList is a class of Collections framework that is defined in the java.util package. It inherits the AbstractList class. It dynamically stores the elements. The advantage of ArrayList is that it has no size limit. It is more flexible than the traditional array. It may have duplicate elements. We can also use all the methods of List interface because it implements the List interface.

We can sort an ArrayList in two ways ascending and descending order. The Collections class provides two methods to sort an ArrayList in Java.

  • sort()
  • reverseOrder()

Collections.sort() Method

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

Syntax

Remember: All elements in the ArrayList must be mutually comparable, else it throws ClassCastException. Here, mutually comparable means the list must have the same type of elements. For example, consider the snippet of the code:

In the above example, we see that a list has four elements out of which three elements are of String type and one is Integer type. The three elements that are in String are mutually comparable but the element that is of Integer type is not comparable with the other three. Hence, the list must have the same type of elements.

Collections.reverseOrder() Method

If we want to sort ArrayList in descending order, Java Collections class provides reverseOrder() method. It allows us to sort the ArrayList in reverse-lexicographic order.

Syntax

It returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Remember that we do not directly invoke the reverseOrder() method. We use it along with the Collection.sort() method, as follows.

Therefore, the sorting of ArrayList in descending order done in two steps, first the ArrayList sorts the data in ascending order, after that the sorted data is reversed by the reverseOrder() method.

Let's create programs that sort ArrayList in ascending order.

Sort ArrayList in Ascending Order

In the following example, we have created an ArrayList of type String and added some elements into it. After that we have invoked sort() method of the Collections class and passed the object of the ArrayList class i.e., list that sorts the elements in the ascending order.

// File Name: SortArrayListExample1.java

Output:

Before Sorting: [Volkswagen, Toyota, Porsche, Ferrari, Mercedes-Benz, Audi, Rolls-Royce, BMW]
After Sorting: [Audi, BMW, Ferrari, Mercedes-Benz, Porsche, Rolls-Royce, Toyota, Volkswagen]

Let's see another example that sorts an ArrayList of Integer type.

SortArrayListExample2.java

Output:

ArrayList Before Sorting:
55
34
98
67
39
76
81
ArrayList After Sorting:
34
39
55
67
76
81
98

Sort ArrayList in Descending Order

In the following example, we have created an ArrayList of type String and added some elements into it. After that we have invoked reverseOrder() method along with the sort() method of the Collections class and passed the object of the ArrayList class i.e., list that sorts the elements in the descending order.

SortArrayListExample3.java

Output:

Before Sorting: [Data Science, Testing, C#, Basic Language, UML, Algorithms, Computer Networks, Python]
After Sorting: [UML, Testing, Python, Data Science, Computer Networks, C#, Basic Language, Algorithms]

SortArrayListExample4.java

Output:

ArrayList Before Sorting:
566
230
123
110
689
12
95
ArrayList After Sorting:
689
566
230
123
110
95
12

Implementing Comparable Interface

If you have a custom class and want to sort objects of that class in an ArrayList, you can make the class implement the Comparable interface. This interface requires implementing the compareTo() method, which defines the natural ordering of objects.

Here's an example of sorting a list of custom objects using the Comparable interface:

File Name: ImplementingCompartable.java

Output:

Sorted ArrayList: [Student{name='Alice', age=20}, Student{name='Bob', age=22}, Student{name='Charlie', age=21}]

Using Comparator Interface

If you want to sort objects based on criteria other than their natural ordering, you can use the Comparator interface. This interface requires implementing the compare() method, which compares two objects based on a specified criterion.

Here's an example of sorting a list of custom objects using a Comparator:

File Name: UsingComparator.java

Output:

Sorted ArrayList: [Student{name='Alice', age=20}, Student{name='Bob', age=22}, Student{name='Charlie', age=21}]

Conclusion

Sorting an ArrayList in Java is a fundamental operation that can be achieved using various techniques. Whether we are dealing with built-in types or custom objects, Java offers flexible methods to sort collections efficiently. By understanding these techniques, we can effectively manage and manipulate data in your Java programs.


Java sort ArrayList MCQ

1. Which method is used to sort an ArrayList in Java?

  1. Arrays.sort()
  2. Collections.sort()
  3. Sort.arraylist()
  4. Arraylist.sort()

Answer: b

Explanation: The Collections.sort() method is used to sort an ArrayList in Java. It sorts the elements in their natural order if they implement the Comparable interface.


2. How can you sort an ArrayList of custom objects by a specific field?

  1. By implementing Comparable in the custom class
  2. By using a custom Comparator
  3. Both a and b
  4. By using Collections.sort() without any parameters

Answer: c

Explanation: We can sort an ArrayList of custom objects by a specific field either by implementing the Comparable interface in the custom class or by using a custom Comparator.


3. What is the output of the following code?

  1. [3, 1, 4, 1, 5, 9]
  2. [1, 1, 3, 4, 5, 9]
  3. [9, 5, 4, 3, 1, 1]
  4. [1, 3, 4, 1, 5, 9]

Answer: b

Explanation: The code sorts the ArrayList in ascending order, resulting in [1, 1, 3, 4, 5, 9].


4. How can you sort an ArrayList of strings ignoring case differences?

  1. Using Collections.sort() with a custom Comparator
  2. Using Collections.sort() directly
  3. Using Arrays.sort()
  4. Using ArrayList.sort()

Answer: a

Explanation: To sort an ArrayList of strings while ignoring case differences, you can use Collections.sort() with a custom Comparator that implements case-insensitive comparison.


5. Which Comparator method is used for sorting in reverse order?

  1. Collections.reverseOrder()
  2. Comparator.reverse()
  3. Collections.descendingOrder()
  4. ArrayList.reverse()

Answer: a

Explanation: The Collections.reverseOrder() method returns a Comparator that sorts the elements in reverse order.


Next TopicJava ArrayList