Sort Elements in ArrayList, LinkedList, Vector

Let us sort elements in ArrayList in the increasing order. Not only ArrayList, but also LinkedList. The code for both of them is same and dead easy as well. All you need to do is to remember this sweet method prototype. The following method will sort the elements according to their compareTo() method. For elements in a list to be sorted, those elements must be implementing the java.lang.Comparable interface.

SortList.java

import java.util.*;
class SortList {
    public static void main(String args[]) {

        // Create an ArrayList containing String type elements

        ArrayList < String > aList = new ArrayList < String > ();


        // Add elements to the ArrayList aList   

        aList.add("Gowtham");
        aList.add("Gutha's");
        aList.add("java");
        aList.add("-");
        aList.add("demos");
        aList.add(".");
        aList.add("blogspot");
        aList.add(".");
        aList.add("com");


        // Print elements before sorting

        System.out.println("\nElements before sorting");
        System.out.println("--------------------");

        for (int i = 0; i < aList.size(); i++) {
            System.out.println(aList.get(i));
        }



        // Sort the elements in ArrayList

        Collections.sort(aList);


        // Print the sorted elements

        System.out.println("\nElements in sorted order");
        System.out.println("--------------------");


        for (int i = 0; i < aList.size(); i++) {
            System.out.println(aList.get(i));
        }


    }
}

Output of the program

Elements before sorting  
--------------------  
Gowtham  
Gutha's  
java  
-  
demos  
.  
blogspot  
.  
com  
  
Elements in sorted order  
--------------------  
-  
.  
.  
Gowtham  
Gutha's  
blogspot  
com  
demos  
java

Explaining the program

The java.util.Collections class contains a static method called sort() which takes a java.util.List object and sorts this according to the compareTo() method written in the element class. Here, the elements are of type java.lang.String and hence for sorting the compareTo() method in the String class is used. As said earlier, for this to happen the element class must be implementing the java.lang.Comparable interface. The algorithm used for developing this method is a modified version of the mergesort.

The List that is sent as parameter should be modifiable because re arranging the elements has to take place.

To sort a LinkedList the way is the same. To try the above program with LinkedList Replace All the ArrayList with LinkedList and for Vector replace with Vector. Save the program, compile and then execute. That’s it. Remember that the Collections.sort() takes List object which can be LinkedList or ArrayList or Vector and any class implementing the List interface.

Also see sorting an array in increasing order

No comments: