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 to Find the Length/Size of an ArrayList
Given an ArrayList in Java, the task is to write a Java program to find the length or size of the ArrayList. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: 5 Input: ArrayList: [geeks, for, geeks] Output: 3 ArrayList - An ArrayList is a part of the collection framework and is present in java.uti
2 min read
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
Java Program to Convert ArrayList to LinkedList
Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5]
6 min read
Java Program for Bitonic Sort
Bitonic Sequence is a sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 â¦..<= xi and xi >= xi+1â¦.. >= xn-1 A sequence, sorted in increasing order is co
4 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
JavaScript - Sort an Array of Strings
Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
3 min read
Java Program for Merge Sort
Merge Sort is a divide-and-conquer algorithm. It divides the input array into two halves, calls itself the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are
3 min read