Java Program to Sort an ArrayList
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.
- Comparable
- Comparator
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
Please Login to comment...