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 Reverse ArrayList in Java with Example

1. Program for Sorting String ArrayList

Here we are sorting the ArrayList of String type. 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[]){
    ArrayList<String> listofcountries = new ArrayList<String>();
    listofcountries.add("USA");
    listofcountries.add("UK");
    listofcountries.add("India");
    listofcountries.add("Canada");
    /*Unsorted List*/
    System.out.println("Before Sorting:");
    for(String counter: listofcountries){
   System.out.println(counter);
  }

    /* Sort statement*/
    Collections.sort(listofcountries);

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

Output :
Before Sorting:
USA
UK
India
Canada
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 IntegerArrayList  {

 public static void main(String args[]){
    ArrayList<Integer> arraylist = new ArrayList<Integer>();
    arraylist.add(5);
    arraylist.add(7);
    arraylist.add(8);
    arraylist.add(3);
    /* ArrayList before the sorting*/
    System.out.println("Before Sorting:");
    for(int counter: arraylist){
   System.out.println(counter);
  }

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

    /* ArrayList after sorting*/
    System.out.println("After Sorting:");
    for(int counter: arraylist){
   System.out.println(counter);
  }
 }
}

Output:

Before Sorting:
5
7
8
3
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 .
For more java articles ,Click here to Subscribe JavaHungry