21 Sept 2012

Sorting LinkedList in java example

import java.util.LinkedList;
import java.util.Collections;
 
public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> ranks = new LinkedList<String>();
        ranks.add("5");
        ranks.add("3");
        ranks.add("1");
        ranks.add("6");
        ranks.add("2");
        ranks.add("4");
 
        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String rank : ranks) {
            System.out.println("rank = " + rank);
        }
 
        //
        // Sort the elements of linked list based on its data
        // natural order.
        //
        Collections.sort(ranks);
 
        System.out.println("After sorting:");
        System.out.println("===============");
        for (String rank : ranks) {
            System.out.println("rank = " + rank);
        }
    }
}

The result of the program are:

Before sorting:
===============
rank = 5
rank = 3
rank = 1
rank = 6
rank = 2
rank = 4
After sorting:
===============
rank = 1
rank = 2
rank = 3
rank = 4
rank = 5
rank = 6

0 comments:

Post a Comment