java

How to sort items in a stream with Stream.sorted()

Just like lists or arrays, you would also like to sort streams. Of course, the Java 8 Stream API offers a simple solution.
 

Sort stream with Comparator as lambda expression

The Stream.sorted() method expects a comparator. Since Comparator is a functional interface, we can pass a lambda expression instead of a class:

List myList = Arrays.asList(
        new Person("1", "Alex", "Kourti"),
        new Person("2", "Thomas", "Nibosi"),
        new Person("3", "Jean", "Fawdor"),
        new Person("4", "Emily", "Somilaro")
);

List firstNames = myList.stream()
    .sorted((p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()))
    .map(p -> p.getFirstName())
    .collect(Collectors.toList());

System.out.println(firstNames);

Output:

[Alex, Emily, Jean, Thomas]

The list “myList” is easily sorted by first name using the lambda expression :

(p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName())
 

Sort the stream in the natural order of the elements

If the class itself implements the Comparable interface, we don’t need to pass the comparator or lambda expression:

List firstNames = myList.stream()
    .sorted()
    .map(p -> p.getFirstName())
    .collect(Collectors.toList());

System.out.println(firstNames);

Output:

[Alex, Emily, Jean, Thomas]

In this case, the Person class must implement the Comparable interface, which is provided by the compareTo() method:

@Override
public int compareTo(@NotNull Object o) {
    return firstName.compareTo(((Person) o).getFirstName());
}
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *