Organizational Research By

Surprising Reserch Topic

How to sort ArrayList in Java


In this tutorial we have shared the examples of sorting an String ArrayList and Integer ArrayList.

Also Read:

Sort ArrayList in descending order
Sort ArrayList of Objects using Comparable and Comparator
Example 1: Sorting of ArrayList

Here we are sorting the ArrayList of String type. We are doing it by simply calling the Collections.sort(arraylist) method. The output List will be sorted alphabetically.

import java.util.*;
public class Details  {

    public static void main(String args[]){
       ArrayList listofcountries = new ArrayList();
       listofcountries.add("India");
       listofcountries.add("US");
       listofcountries.add("China");
       listofcountries.add("Denmark");

       /*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:
India
US
China
Denmark
After Sorting:
China
Denmark
India
US
Example 2: Sorting of ArrayList

The same Collections.sort() method can be used for sorting the Integer ArrayList as well.

import java.util.*;
public class ArrayListOfInteger  {

    public static void main(String args[]){
       ArrayList arraylist = new ArrayList();
       arraylist.add(11);
       arraylist.add(2);
       arraylist.add(7);
       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:
11
2
7
3
After Sorting:
2
3
7
11
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
66 views



Related Hot Questions



Government Jobs Opening


...