Java Reference
In-Depth Information
■
Java 8 added a default method called
sort(Comparator<? super E> c)
in the
List<E>
interface that allows
you to sort a
List
without using the
Collections
class.
Tip
The following snippet of code demonstrates how to sort a
List
:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
...
List<String> list = new ArrayList<>();
list.add("John");
list.add("Richard");
list.add("Donna");
list.add("Ken");
System.out.println("List: " + list);
// Uses Comparable implementation in String to sort the list in natural order
Collections.sort(list);
System.out.println("Sorted List: " + list);
List: [John, Richard, Donna, Ken]
Sorted List: [Donna, John, Ken, Richard]
The following snippet of code sorts the same list in ascending order of the length of their elements using the
sort()
method in the
List
interface:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
...
List<String> list = new ArrayList<>();
list.add("John");
list.add("Richard");
list.add("Donna");
list.add("Ken");
System.out.println("List: " + list);
// Uses List.sort() method with a Comparator
list.sort(Comparator.comparing(String::length));
System.out.println("Sorted List: " + list);
List: [John, Richard, Donna, Ken]
Sorted List: [Ken, John, Donna, Richard]