How do I 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 org.kodejava.example.util;

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

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList grades = new LinkedList();
        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

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply