Java Program to Sort an ArrayList
Last Updated :
17 May, 2021
ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unordered manner. In some cases, we need to rearrange the data in an ordered manner.Â
There are two types of ArrayList are there in java. One is ArrayList of Wrapper class objects and another one is ArrayList of user-defined objects. We will see the sorting of both types of ArrayList. Let's start with the first one.
- Sorting an ArrayList of Wrapper Class objects.
- Ascending Order
- Descending Order
- Sorting an ArrayList of User-defined objects.
Type 1: Sorting an ArrayList of Wrapper Class objects
An ArrayList of Wrapper class object is nothing but an ArrayList of objects like String, Integers, etc. An ArrayList can be sorted in two ways ascending and descending order. The collection class provides two methods for sorting ArrayList. sort() and reverseOrder() for ascending and descending order respectively.
1(A)Ascending Order
This sort() Method accepts the list object as a parameter and it will return an ArrayList sorted in ascending order. The syntax for the sort() method is like below.Â
Collections.sort(objectOfArrayList);
All elements in the ArrayList must be mutually comparable, else it throws ClassCastException. Here, mutually comparable means all the items of the list having the same datatype.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(132);
list.add(321);
list.add("India");
In the above example, we see that a list has three elements out of which two elements are of Integer type and one is String type. The two elements that are in Integer are mutually comparable but the element that is of String type is not comparable with the other two. In this case, We can get a ClassCastException. Hence, the list must have the same type of elements.
Let's consider the following example to understand sorting.
Java
// Java Program to Sort an ArrayList
// import java.util package
import java.util.*;
class GFG {
// Main driver method
public static void main(String[] args)
{
// Define an objects of ArrayList class
ArrayList<String> list = new ArrayList<String>();
// Adding elements to the ArrayList
list.add("India");
list.add("Pakistan");
list.add("Srilanka");
list.add("USA");
list.add("Australia");
list.add("Japan");
// Printing the unsorted ArrayList
System.out.println("Before Sorting : " + list);
// Sorting ArrayList in ascending Order
Collections.sort(list);
// printing the sorted ArrayList
System.out.println("After Sorting : " + list);
}
}
Output:
Before Sorting : [India, Pakistan, Srilanka, USA, Australia, Japan]
After Sorting : [Australia, India, Japan, Pakistan, Srilanka, USA]
1(B) Descending Order
To sort an ArrayList in descending order we use reverseOrder() method as an argument of a sort() method. we can't directly call the reverseOrder() method. This method takes two parameters one is an object of ArrayList and the second parameter is the Collections.reversOrder() method. This method will return ArrayList in Descending order. Similar to the sort() method ArrayList must be mutually comparable, else it throws ClassCastException.
Collections.sort(objectOfArrayList, Collections.reverseOrder());
Here this method first sorts the items in ascending order then it will reverse the order of sorted items.
Java
// Java Program to Sort an ArrayList
// Importing generic java files
import java.util.*;
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Define an objects of ArrayList class
ArrayList<Integer> list = new ArrayList<Integer>();
// Adding elements to the ArrayList
list.add(410);
list.add(250);
list.add(144);
list.add(967);
list.add(289);
list.add(315);
// Printing the unsorted ArrayList
System.out.println("Before Sorting : " + list);
// Sorting ArrayList in descending Order
Collections.sort(list, Collections.reverseOrder());
// Printing the sorted ArrayList
System.out.println("After Sorting : " + list);
}
}
Output:
Before Sorting : [410, 250, 144, 967, 289, 315]
After Sorting : [967, 410, 315, 289, 250, 144]
2. Sorting an ArrayList of User-defined objects
An ArrayList of User-defined objects are nothing but an ArrayL.ist of custom objects. In Java, there are two interfaces that can be used to sort collection elements. Comparable and Comparator.
2(A) Comparable
Comparable provides a single sorting sequence. If we use Comparable it will affect the original class. Comparable Interface provides compareTo() method to sort elements. In java, comparable is provided by java.lang package. We can sort the ArrayList by invoking Collections.sort(List) method.
Example: Sorting is done based on number of cars in stock.Â
Java
// Java Program to Sort an ArrayList
// Importing generic java files
import java.util.*;
// Implements comparable interface into custom class
class Car implements Comparable<Car> {
int ModalNo;
String name;
int stock;
// Parameterized constructor of the class
Car(int ModalNo, String name, int stock)
{
this.ModalNo = ModalNo;
this.name = name;
this.stock = stock;
}
// Override the compareTo method
public int compareTo(Car car)
{
if (stock == car.stock)
return 0;
else if (stock > car.stock)
return 1;
else
return -1;
}
}
// Main driver method
class GFG {
// Main driver method
public static void main(String[] args)
{
// Create the ArrayList object
ArrayList<Car> c = new ArrayList<Car>();
c.add(new Car(2018, "Kia", 20));
c.add(new Car(2020, "MG", 13));
c.add(new Car(2013, "creta", 10));
c.add(new Car(2015, "BMW", 50));
c.add(new Car(2017, "Audi", 45));
// Call the sort function
Collections.sort(c);
// Iterate over ArrayList using for each loop
for (Car car : c) {
// Print the sorted ArrayList
System.out.println(car.ModalNo + " " + car.name
+ " " + car.stock);
}
}
}
 Â
Output:
Â
2013 creta 10
2020 MG 13
2018 Kia 20
2017 Audi 45
2015 BMW 50
Â
2(B) ComparatorÂ
Â
Comparator provides multiple sorting sequences. The comparator will not affect the original class. Comparator provides compare() method to sort elements. In java, comparable is provided by java.util package. We can sort the ArrayList by invoking Collections.sort(List, Comparator) method. Â Let's take one example.
Â
Java
// Java Program to Sort an ArrayList
// Step 1: ImportingDB files
import java.util.*;
// Class 1: Parent Class
class Car {
int ModalNo;
String name;
int stock;
// Parameterized constructor
Car(int ModalNo, String name, int stock)
{
this.ModalNo = ModalNo;
this.name = name;
this.stock = stock;
}
}
// Class 2: Child class
// creates the comparator for comparing stock value
class StockComparator implements Comparator<Car> {
// Function to compare
public int compare(Car c1, Car c2)
{
if (c1.stock == c2.stock)
return 0;
else if (c1.stock > c2.stock)
return 1;
else
return -1;
}
}
class GFG {
// Main driver method
public static void main(String[] args)
{
// Create the ArrayList object
ArrayList<Car> c = new ArrayList<Car>();
c.add(new Car(2018, "Kia", 20));
c.add(new Car(2020, "MG", 13));
c.add(new Car(2013, "creta", 10));
c.add(new Car(2015, "BMW", 50));
c.add(new Car(2017, "Audi", 45));
// Call the sort function
Collections.sort(c, new StockComparator());
// For each loop to iterate
for (Car car : c) {
// Print the sorted ArrayList
System.out.println(car.stock + " " + car.name
+ " " + car.ModalNo);
}
}
}
Output:
10 creta 2013
13 MG 2020
20 Kia 2018
45 Audi 2017
50 BMW 2015
Similar Reads
Java Program for Insertion Sort Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. In this article, we will write the program on Insertion Sort in Java.Please refer complete article on Insertion Sort for more details! Algorithm of Insertion SortThe algorithm of Insertion Sort is men
2 min read
How to sort an ArrayList in Ascending Order in Java Given an unsorted ArrayList, the task is to sort this ArrayList in ascending order in Java. Examples: Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Output: Sorted ArrayList: [A computer portal, For, ForGeeks, Geeks, GeeksForGeeks] Input: Unsorted ArrayList: [Gee
2 min read
How to sort an Array of Strings in Java Array Of StringsTo sort an array of strings in Java, we can use Arrays.sort() function. Java // A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; // Driver Class public class SortE
3 min read
How to sort an ArrayList in Descending Order in Java Given an unsorted ArrayList, the task is to sort this ArrayList in descending order in Java. Examples: Input: Unsorted ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Output: Sorted ArrayList: [GeeksForGeeks, Geeks, ForGeeks, For, A computer portal] Input: Unsorted ArrayList: [Ge
2 min read
How to Sort an Array in Scala? Sorting arrays effectively is essential for many applications, regardless of whether you're working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situati
5 min read
Arrays.sort() in Java The Arrays.sort() method is used for sorting the elements in an Array. It has two main variations: Sorting the entire array (it may be an integer or character array) Sorting a specific range by passing the starting and ending indices.Below is a simple example that uses the sort() method to arrange a
6 min read
How to Sort a list in Scala? Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
2 min read
Java Program for Selection Sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.Algorithm for Selection SortImplementation of Selection Sort in Java is mentioned below:Step 1: Array arr with N sizeStep 2: Init
2 min read
Sort an Array in Java using Comparator A Comparator is an object that can be used to compare two objects and determine their order. We can use a Comparator to sort a list of objects in any order we can choose, not just in ascending order.Examples:Array(Ascending Order): Input: arr = (4, 2, 5, 1, 3) Output: [1, 2, 3, 4, 5] Array(Descendin
4 min read
How to Sort an Arrays of Object using Arrays.sort() To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array st
3 min read