# Sort a list

`static<T extends Comparable<? super T>>void sort(List<T> list)`
Sorts the specified list into ascending order, according to the natural ordering of its elements.
`static<T> void sort(List<T> list, Comparator<? super T> c)`
Sorts the specified list according to the order induced by the specified comparator.
``````
import java.util.Collections;
import java.util.Comparator;

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

Comparator<Integer> r = Collections.reverseOrder();

Collections.sort(ll, r);

System.out.print("List sorted in reverse: ");
System.out.print(ll);
}
}

``````

The output:

``````
List sorted in reverse: [20, 8, -8, -20]
``````

Sort elements of ArrayList

``````
import java.util.ArrayList;
import java.util.Collections;

public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
Collections.sort(arrayList);

System.out.println(arrayList);
}
}
``````

The output:

``````
[1, 2, 3, 4, java2s.com]
``````

Sort elements of Vector

``````
import java.util.Vector;
import java.util.Collections;

public class Main {
public static void main(String[] args) {
Vector v = new Vector();
Collections.sort(v);

System.out.println(v);
}
}
``````

The output:

``````
[1, 2, 3, 5, java2s .com ]
``````

Sort ArrayList in descending order using comparator

``````
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
Comparator comparator = Collections.reverseOrder();
System.out.println("Before: " + arrayList);
Collections.sort(arrayList, comparator);
System.out.println("After sorting: " + arrayList);
}
}
``````

The output:

``````
Before: [A, B, C, D, java2s.com]
After sorting: [java2s.com, D, C, B, A]
``````

Sort Vector in descending order using comparator

``````
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

public class Main {
public static void main(String[] args) {
Vector v = new Vector();
Comparator comparator = Collections.reverseOrder();
System.out.println("Before sorting: " + v);
Collections.sort(v, comparator);
System.out.println("After sorting: " + v);
}
}
``````

The output:

``````
Before sorting: [1, 2, 3, 4, j ava2s.com]
After sorting: [j ava2s.com, 4, 3, 2, 1]
``````
Home
Java Book
Collection

Collections: