EN
Java 8 - sort list with stream.sorted()
0
points
In this article, we would like to show you how to sort lists with stream.sorted()
in Java 8.
Quick solution
Natural order:
List<String> list = Arrays.asList("C", "A", "D", "B");
List<String> sorted = list
.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sorted); // [A, B, C, D]
Reverse order:
List<String> sorted = list
.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(sorted); // [D, C, B, A]
1. Natural order
In this example, we use stream.sorted()
method to sort the list
in alphabetical order and save the result as a new list - sorted
.
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) throws IOException {
List<String> list = Arrays.asList("C", "A", "D", "B");
System.out.println("Original list: " + list); // [C, A, D, B]
List<String> sorted = list
.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted list: " + sorted); // [A, B, C, D]
}
}
Output:
Original list: [C, A, D, B]
Sorted list: [A, B, C, D]
Note:
By default, the
sorted()
method usesComparator.naturalOrder()
.
2. Reverse order
In this example, we use stream.sorted()
method with Comparator.reverseOrder()
to sort the list
in reverse order and save the result as a new list - sorted
.
package tmpOperations2;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) throws IOException {
List<String> list = Arrays.asList("C", "A", "D", "B");
System.out.println("Original list: " + list); // [C, A, D, B]
List<String> sorted = list
.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Sorted list: " + sorted); // [D, C, B, A]
}
}
Output:
Original list: [C, A, D, B]
Sorted list: [D, C, B, A]