Saturday, March 23, 2024

How to sort ArrayList in Java? Examples

Hello Java programmers, sorting ArrayList in Java is not difficult; there are multiple ways to sort a given ArrayList in Java. For example you can use  the Collections.sort() method to  sort ArrayList in ascending and descending order in Java. The  Collections.sort() the method optionally accepts a Comparator. If provided, it uses Comparators' compare() method to compare Objects stored in Collection to compare with each other; in case of no explicit Comparator, Comparable interfaces' compareTo() method is used to compare objects from each other. If objects stored in ArrayList don't implement Comparable, they can not be sorted using the Collections.sort() the method in Java.

 

How to Sort An ArrayList in Java?Examples

Here is a complete code example of How to sort ArrayList in Java; in this Sorting, we have used Comparable method of String for sorting String on their natural order, You can also use Comparator in place of Comparable to sort String on any other order than natural ordering like in reverse order by using Collections.reverseOrder() or insensitive order by using String.CASE_INSENSITIVE_COMPARATOR.


1.1 Sorting ArrayList in Ascending Order in Java

First, let's see how to sort an array in ascending order in Java using the Collections.sort() method. This method is overloaded, which means you can sort the ArrayList in natural order by leveraging the default comparator, which sorts the list in the natural order, and you can use the Collections.sort(list, Comparator) to sort the ArrayList in custom order defined by Comparator. 

Since we are sorting ArrayList of String which implements a Comparable interface, we can use the first method to sort the ArrayList string into the natural order or ascending order.  You can also use this method to sort an ArrayList of Integer into increasing order because that's the default order for an Integer object. 

import java.util.*;

class Main {
  public static void main(String[] args) {
    
    List<Integer> listofYears = new ArrayList<Integer>();
    listofYears.add(2021);
    listofYears.add(2019);
    listofYears.add(2018);
    listofYears.add(2020);

    // print the ArrayList before sorting
    System.out.println("ArrayList before sorting");
    System.out.println(listofYears);


    // sorting an ArrayList of Integer in ascending order
    Collections.sort(listofYears);
    
    // print the ArrayList after sorting
    System.out.println("ArrayList after sorting");
    System.out.println(listofYears);
  }
}

Output:
Output:
java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
ArrayList before sorting
[2021, 2019, 2018, 2020]
ArrayList after sorting
[2018, 2019, 2020, 2021]

1.2 Sorting ArrayList in Descending Order in Java

Now that you know how to sort ArrayList in ascending order, it's time to sort the given ArrayList into descending order. For that, we'll use the overloaded version of the Collections.sort() method, which accepts a Comparator. 

Don't worry, you don't need to create your own Comparator; in fact, you can use the Collections.reverseOrder() method, which returns a reverse order comparator that can be used to sort an ArrayList on descending order in Java. 


import java.util.*;

class Main {
  public static void main(String[] args) {
    
    List<Integer> listofYears = new ArrayList<Integer>();
    listofYears.add(2021);
    listofYears.add(2019);
    listofYears.add(2018);
    listofYears.add(2020);

    // print the ArrayList before sorting
    System.out.println("ArrayList before sorting");
    System.out.println(listofYears);


    // sorting an ArrayList of Integer in descending order
    Collections.sort(listofYears, Collections.reverseOrder());
    
    // print the ArrayList after sorting
    System.out.println("ArrayList after sorting");
    System.out.println(listofYears);
  }
}


Output:
java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
ArrayList before sorting
[2021, 2019, 2018, 2020]
ArrayList after sorting
[2021, 2020, 2019, 2018]

How to sort ArrayList in Java? Examples



Java Program to Sort an ArrayList of String in Java

Now that you know the mechanism to sort an ArrayList of objects into both ascending and descending order, it's time to take a look at the complete Java program, which you can copy-paste in your Eclipse or IntelliJIDEA IDEA and run it. You can also save this in a Java source file and run it from the command prompt. 

import java.util.ArrayList;
import java.util.Collections;
/**
 *
 * Java program to demonstrate How to sort ArrayList in Java
 * in both ascending and descending order by using 
 *  core Java libraries.
 *
 * @author Javin
 */

public class CollectionTest {

   
    public static void main(String args[]) {
   
        //Creating and populating ArrayList in Java for Sorting
        ArrayList<String> unsortedList = new ArrayList<String>();
       
        unsortedList.add("Java");
        unsortedList.add("C++");
        unsortedList.add("J2EE");
       
        System.err.println("unsorted ArrayList in Java : " + unsortedList);
       
        //Sorting ArrayList in ascending Order in Java
        Collections.sort(unsortedList);
        System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);
       
        //Sorting ArrayList in descending order in Java
        Collections.sort(unsortedList, Collections.reverseOrder());
        System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
    }
}
Output:
unsorted ArrayList in Java : [Java, C++, J2EE]
Sorted ArrayList in Java - Ascending order : [C++, J2EE, Java]
Sorted ArrayList in Java - Descending order : [Java, J2EE, C++]

That's all on How to Sort ArrayList in Java. We have seen example to sort an ArrayList in both ascending and descending order. Just remember that Collections.sort() will sort the ArrayList in ascending order, and if you provide a reverse comparator, it will sort the ArrayList in descending order in Java.

From JDK 8 onward you can also use Stream.sort() method to sort a List by converting List to Stream and then collecting the sorted Stream into another List. You can also use List.sort() method to sort a given List in Java. This is a new method and it was added on Java 8. 


Other Java Collection tutorials:


3 comments:

  1. I have a List of Integers and a List of String, How can I sort them according to there natural order e.g. Sorting Integer List with numeric ascending order and Sorting String List with alphabetic order?

    ReplyDelete
  2. This is indeed a good example to sort an ArrayList of String alphabetically, but this will also work in case of Integer, Date, or any other value type? I believe since it is using Comparable it will sort in the order defined there, as String Comparable sorts data alphabetically but Integer will be in increasing order and Date may be in chronological order. Correct me if I am wrong.

    ReplyDelete
  3. Simple Collections.reverse(unsortedList) after the first sort will sort it as per descending

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.