DoubleStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
Syntax :
DoubleStream sorted()
Where, DoubleStream is a sequence of primitive double-valued
elements. This is the double primitive specialization of Stream.
Return Value : DoubleStream sorted() method returns the new stream having the elements in sorted order.
Example 1 : Using DoubleStream sorted() to sort the numbers in given DoubleStream.
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream = DoubleStream.of( 10.2 , 9.3 , 8.4 ,
7.5 , 6.6 );
stream.sorted().forEach(System.out::println);
}
}
|
Output:
6.6
7.5
8.4
9.3
10.2
Example 2 : Using DoubleStream sorted() to sort the random numbers generated by DoubleStream generator().
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
public static void main(String[] args)
{
DoubleStream stream = DoubleStream.generate(()
-> ( double )(Math.random() * 10000 )).limit( 5 );
stream.sorted().forEach(System.out::println);
}
}
|
Output:
1279.6146863795122
6927.016817313592
7037.390703089559
8374.314582282514
9112.609381925824