Sort elements of linkedlist in java (ascending & descending order)

  • The LinkedList class extends AbstractSequentialList and implements the List interface.
  • Given an LinkedList, we would like to sort elements of linkedlist in ascending and descending order.

Program – Sort linked list in ascending & descending order

package org.learn.collection.list.linkedlist;

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

public class SortElementInLinkedList {

 public static void main(String[] args) {
  LinkedList<String> LinkedList = new LinkedList<>();
  LinkedList.add("archery");
  LinkedList.add("golf");
  LinkedList.add("diving");
  
  System.out.println("Sort elements of arrayList: ");
  demoSortMethod(LinkedList);  
 } 

 private static void demoSortMethod(LinkedList<String> linkedList) {
  //[archery, golf, diving]
  System.out.println("Orignal LinkedList:" + linkedList);
  Collections.sort(linkedList);
  // [archery, diving, golf]
  System.out.println("1. Sort ascending order: " + linkedList);

  Collections.sort(linkedList, Collections.reverseOrder());
  // [golf, diving, archery]
  System.out.println("2. Sort desending order: " + linkedList);
 } 
}

Output – Sort linkedlist in ascending & descending order

Sort elements of arrayList: 
Orignal LinkedList:[archery, golf, diving]
1. Sort ascending order: [archery, diving, golf]
2. Sort desending order: [golf, diving, archery]
Scroll to Top