java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to sort LinkedList elements?

To sort the elements of LinkedList we can use the Collections.sort(List list) static methods. The default order of the sorting is a descending order.

package com.javacoderanch.example.util;

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

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<String>();
        grades.add("E");
        grades.add("C");
        grades.add("A");
        grades.add("F");
        grades.add("B");
        grades.add("D");

        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        //
        // Sort the elements of linked list based on its data
        // natural order.
        //
        Collections.sort(grades);

        System.out.println("After sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are:

Before sorting:
===============
Grade = E
Grade = C
Grade = A
Grade = F
Grade = B
Grade = D
After sorting:
===============
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F