Stream interface provides a sorted() method to sort a list. The sorted() method returns a sorted stream according to the natural order. If the elements are not comparable, it throws java.lang.ClassCastException.
Stream<
T<
> sorted()
Stream<
T<
> sorted(Comparator<
? Super T
> comparator)
//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class StreamSortedExample {
public static void main (
String
args[]){
Integer
[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
List
Integer
> sortedList =
Arrays.asList(numbers).stream()
.sorted()
.collect( Collectors.toList() );
System.out.println( ""Sorted list : "+ sortedList );
}
}
Output:
Sorted list : [1, 2, 5, 7, 11, 13, 16, 20, 28, 100, 440]
//Importing required classes import java.util.*; import java.io.*; import java.util.stream.*; public class StreamSortedExample { public static void main (String args[]){ Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 }; List<
Integer
> sortedList = Arrays.asList( numbers ).stream() .sorted() //forEach with method reference .forEach( System.out :: println ); } } Output: 1 2 5 7 11 13 16 20 28 100 440
public class Students { private
Integer
age; private
String
name; Students(
Integer
age,
String
name){ this.age=age; this.name=name; } public String toString() { return this.age + ", "+ this.name; } } //Importing required classes import java.util.*; import java.io.*; import java.util.stream.*; public class SortedExampleWithComparator { public static void main (
String
args[]){ List<
Students
> studentsList = new ArrayList<
Students
>(); studentsList.add( new Students( 18, "Pankaj" )); studentsList.add( new Students( 20, "Prakash" )); studentsList.add( new Students( 16, "Karim" )); studentsList.add( new Students( 19, "Shyam" )); studentsList .stream() //comparator .sorted(( s1, s2 ) -> s1.age.compareTo( s2.age )) //forEach with method reference .forEach( System.out :: println ); } } Output: 16, Karim 18, Pankaj 19, Shyam 20, Prakash