How to sort an ArrayList in Java with Example

In this tutorial we will learn how to sort an ArrayList in java. We will sort the String ArrayList and Integer ArrayList.

Read Also :  How to Sort ArrayList in Descending Order in Java

How to Sort ArrayList using Comparable and Comparator

1. Program for Sorting String ArrayList

Here we are showing the sorting of the ArrayList of String type i.e ArrayList. We will use the Collections.sort(list) method.  In this case the output list will be sorted alphabetically.


import java.util.*;
public class SortStringArrayList  {

 public static void main(String args[]){ 
    /*Creating String ArrayList Object*/
    ArrayList<String> countrieslist = new ArrayList<String>();
    countrieslist.add("USA");
    countrieslist.add("UK");
    countrieslist.add("India");
    countrieslist.add("Canada"); 
    
    /*Unsorted Countries List*/
    System.out.println("Countries List Before Sorting:");
    for(String counter: countrieslist){
        System.out.println(counter);
    }

    /* Sort ArrayList using 
       Collections.sort(list) method*/
    Collections.sort(countrieslist);

    /* Sorted Countries List*/
    System.out.println("Countries List After Sorting:");
    for(String counter: countrieslist){
       System.out.println(counter);
    }
 }
}

Output :
Countries List Before Sorting:
USA
UK
India
Canada
Countries List After Sorting:
Canada
India
UK
USA

2Program for Sorting Integer ArrayList

We will use the same Collections.sort(list) method to sort the Integer ArrayList.

import java.util.*;
public class SortIntegerArrayList  {

 public static void main(String args[]){ 
    /*Creating Integer ArrayList Object*/
    ArrayList<Integer> al = new ArrayList<Integer>(); 
 
    /*Adding Integer values to
      ArrayList Object*/
    al.add(5);
    al.add(7);
    al.add(8);
    al.add(3); 
 
    /* Integer ArrayList Before Sorting*/
    System.out.println("ArrayList Before Sorting:");
    for(int counter: al){
      System.out.println(counter);
    }

    /* Sorting of arraylist using Collections.sort*/
    Collections.sort(al);

    /* Integer ArrayList After Sorting*/
    System.out.println("ArrayList After Sorting:");
    for(int counter: al){
      System.out.println(counter);
    }
 }
}

Output:

ArrayList Before Sorting:
5
7
8
3
ArrayList After Sorting:
3
5
7
8

Please mention in comments if you know any other way to sort an ArrayList in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry