Collections

how to sort the elements of a LinkedList using the Collections API
Previous Home Next

 



 


 
package r4r.co.in;
import java.util.*;
import java.util.ListIterator;


public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub


LinkedList<Integer> list=new LinkedList<Integer>(); // creating a LinkedList of Integer type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add(50);
list.add(70);
list.add(7);
System.out.println("The contents of the list are :");
ListIterator<Integer> ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}

Collections.sort(list); // sorting the linkedlist list using sort() method of Collections API
System.out.println("The sorted list is as follows:");
ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the sorted list
}



}


}
The output of the above code is as follows:

The contents of the list are :
1
2
50
70
7
The sorted list is as follows:
1
2
7
50
70
Previous Home Next