Close

Java Collections - Collections.sort() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Methods:

public static <T extends Comparable<? super T>> void sort(List<T> list)

Sorts the specified list into the ascending natural ordering of its elements. The specified list must be modifiable, but need not be resizable.



public static <T> void sort(List<T> list,
                            Comparator<? super T> c)

Sorts the specified list according to the order induced by the specified comparator. The specified list must be modifiable, but need not be resizable.


Examples


package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortExample {

public static void main(String... args) {
List<Integer> list = Arrays.asList(210, 120, 33, 4, 50);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}

Output

[210, 120, 33, 4, 50]
[4, 33, 50, 120, 210]




package com.logicbig.example.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortExample2 {

public static void main(String... args) {
List<Integer> list = Arrays.asList(210, null, 33, null, 50);
System.out.println(list);
Collections.sort(list, Comparator.nullsLast(Integer::compare));
System.out.println(list);
}
}

Output

[210, null, 33, null, 50]
[33, 50, 210, null, null]




See Also