Java - Collection Framework List Sorting

Introduction

You can use one of the following two static methods in the Collections class to sort the elements of a List:

<T extends Comparable<? super T>> void sort(List<T> list) sorts the elements in a List by the Comparable interface implemented by the elements in the List.

Each element in the List must implement the Comparable interface and they must be comparable to each other.

<T> void sort(List<T> list, Comparator<? super T> c) accepts a Comparator object to define a custom ordering of the elements.

A default method sort(Comparator<? super E> c) in the List<E> interface can sort a List without using the Collections class.

The sort() method uses a modified mergesort algorithm.

It is a stable sort.

Sorting is guaranteed to give n*log(n) performance, where n is the number of elements in the List.

The following code demonstrates how to sort a List:

Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("XML");
    list.add("Javascript");
    list.add("Json");
    list.add("Java");

    System.out.println("List: " + list);

    // Uses Comparable implementation in String to sort the list in natural
    // order/*from w  ww  .j  a va  2  s  . c  o  m*/
    Collections.sort(list);
    System.out.println("Sorted List: " + list);
  }
}

Result

Related Topics