Languages
[Edit]
EN

Java 8 - sort list with stream.sorted()

0 points
Created by:
Zachariah
298

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 uses Comparator.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]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join