Thursday, 26 July 2012

Sort elements of Java LinkedList Example


This Java Example shows how to sort the elements of java LinkedList object using Collections.sort method.


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

public class SortJavaLinkedListExample {

 public static void main(String[] args) {

  // create an LinkedList object
  LinkedList lList = new LinkedList();

  // Add elements to Arraylist
  lList.add("1");
  lList.add("3");
  lList.add("5");
  lList.add("2");
  lList.add("4");

  /*
   * To sort an LinkedList object, use Collection.sort method. This is a
   * static method. It sorts an LinkedList object's elements into
   * ascending order.
   */
  Collections.sort(lList);

  // display elements of LinkedList
  System.out
    .println("LinkedList elements after sorting in ascending order : ");
  for (int i = 0; i < lList.size(); i++)
   System.out.println(lList.get(i));

 }
}


The output is:




LinkedList elements after sorting in ascending order :
1
2
3
4
5

No comments:

Post a Comment