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.
Natural order:
xxxxxxxxxx
1
List<String> list = Arrays.asList("C", "A", "D", "B");
2
3
List<String> sorted = list
4
.stream()
5
.sorted()
6
.collect(Collectors.toList());
7
8
System.out.println(sorted); // [A, B, C, D]
Reverse order:
xxxxxxxxxx
1
List<String> sorted = list
2
.stream()
3
.sorted(Comparator.reverseOrder())
4
.collect(Collectors.toList());
5
6
System.out.println(sorted); // [D, C, B, A]
In this example, we use stream.sorted()
method to sort the list
in alphabetical order and save the result as a new list - sorted
.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.Arrays;
3
import java.util.List;
4
import java.util.stream.Collectors;
5
6
7
public class Example {
8
9
public static void main(String[] args) throws IOException {
10
List<String> list = Arrays.asList("C", "A", "D", "B");
11
12
System.out.println("Original list: " + list); // [C, A, D, B]
13
14
List<String> sorted = list
15
.stream()
16
.sorted()
17
.collect(Collectors.toList());
18
19
System.out.println("Sorted list: " + sorted); // [A, B, C, D]
20
}
21
}
Output:
xxxxxxxxxx
1
Original list: [C, A, D, B]
2
Sorted list: [A, B, C, D]
Note:
By default, the
sorted()
method usesComparator.naturalOrder()
.
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
.
xxxxxxxxxx
1
package tmpOperations2;
2
3
import java.io.IOException;
4
import java.util.Arrays;
5
import java.util.Comparator;
6
import java.util.List;
7
import java.util.stream.Collectors;
8
9
10
public class Example {
11
12
public static void main(String[] args) throws IOException {
13
List<String> list = Arrays.asList("C", "A", "D", "B");
14
15
System.out.println("Original list: " + list); // [C, A, D, B]
16
17
List<String> sorted = list
18
.stream()
19
.sorted(Comparator.reverseOrder())
20
.collect(Collectors.toList());
21
22
System.out.println("Sorted list: " + sorted); // [D, C, B, A]
23
}
24
}
Output:
xxxxxxxxxx
1
Original list: [C, A, D, B]
2
Sorted list: [D, C, B, A]