Sort a list using stream.sorted() in Java
In this tutorial, we will learn about How to sort a list using stream.sorted() in Java. Before getting into the coding let’s know about java 8.
Introduction to Java 8
Java 8 is nothing but the enhanced major feature of the Java programming language whose initial version was released on 18 March 2014.
It supports advanced features like a new Javascript engine, new streaming APIs, and functional programming.
Let’s know about some basics of the list.
LIST
The list is an interface in Java that maintains an ordered collection of objects.
It is a child interface of collection and allows the positional access and insertion of elements.
stream.sorted()
stream.sorted() is a method that is used for sorting the elements in the stream and sorting according to the natural order.
toList()
- toList() method of Collectors Class is a static method.
- It returns a Collector Interface that gathers the input data onto a new list.
CODE
Now its time to start our coding..
NATURAL ORDER
import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; public class SortList { public static void main(String[] args) { List<String> list=Arrays.asList("Ram","Shyam","Ramesh","Suresh","Aman","Bunti"); List<String> sortedList = list.stream().sorted().collect(Collectors.toList()); for(String x:sortedList) System.out.println(x); } }
OUTPUT
After we run the code, what you will see in the output is given below:
REVERSE ORDER SORTING
List<String> sortedList = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); for(String x:sortedList) System.out.println(x);
OUTPUT
Leave a Reply