Thursday, 4 May 2017

Sort elements in linked list in java

To sort the elements of list be it linked list or array list, you can use
Collections.sort(List list);

Note: 
* Strings are sorted in lexicographic order(see example below)
* Dates are sorted in chronological order(In our example replace String with Date and see the result)
* Integers are sorted in numeric order(In our example replace String with Integer and see the result)


In the given example the sorting method is highlighted in similar background color. Lets look at each step closely. Its pretty simple to sort a list.
Lets have a look.

Source FileSortLinkedList.java


package javaRadarLinkedList;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class SortLinkedList {

      public static void main(String[] args) {
            //create Linked List
            LinkedList<String> javaRadarList= new LinkedList<String>();

            //Add elements to LinkedList
            javaRadarList.add("Java");
            javaRadarList.add("Jquery");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");
             
            //use iterator to traverse list
            System.out.println("Before sorting: " +javaRadarList);
           
            Collections.sort(javaRadarList); //sorting list element
           
            Iterator<String> itrAfterSort = javaRadarList.iterator();

            System.out.println("After Sorting:");
            while(itrAfterSort.hasNext()){
                  String token = itrAfterSort.next();
                  System.out.println(token);
            }

      }

}



OUTPUT:

Before sorting: [Java, Jquery, Spring, Hibernate, EJB]

After Sorting:
EJB
Hibernate
Java
Jquery
Spring

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.