How to Sort List with Stream.sorted in Java


In this example, we will use stream.sorted() to sort a list.

Source Code

package com.beginner.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SortListExample {

    public static void main(String[] args) {

        List l = Arrays.asList("t", "e", "s", "t");
        
		//use Comparator to sort the list
        List list = l.stream().sorted().collect(Collectors.toList());

        //print the list
        list.forEach(System.out::println);

    }
}

Output:

e
s
t
t

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments