Java LinkedList sort in reversed order

Introduction

To sort LinkedList in reversed order in Java

// Create a reverse order comparator.
Comparator<Integer> r = Collections.reverseOrder();
System.out.println(ll);
    
// Sort list by using the comparator.
Collections.sort(ll, r);

Full source

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

public class Main {
  public static void main(String args[]) {

    // Create and initialize linked list.
    LinkedList<Integer> ll = new LinkedList<Integer>();
    ll.add(-8);/*www .j a  va2  s  . c  o m*/
    ll.add(321);
    ll.add(20);
    ll.add(-20);
    ll.add(123);
    ll.add(8);

    // Create a reverse order comparator.
    Comparator<Integer> r = Collections.reverseOrder();
    System.out.println(ll);
    
    // Sort list by using the comparator.
    Collections.sort(ll, r);
    
    System.out.println(ll);
  }
}



PreviousNext

Related