DoubleStream sorted() in Java

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to sort DoubleStream
// using DoubleStream.sorted()
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream
        DoubleStream stream = DoubleStream.of(10.2, 9.3, 8.4,
                                              7.5, 6.6);
  
        // displaying the stream with sorted elements
        // using DoubleStream.sorted() function
        stream.sorted().forEach(System.out::println);
    }
}

chevron_right


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().

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to sort DoubleStream
// using DoubleStream.sorted()
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream by generating
        // random elements using DoubleStream.generate()
        DoubleStream stream = DoubleStream.generate(()
          -> (double)(Math.random() * 10000)).limit(5);
  
        // displaying the stream with sorted elements
        // using DoubleStream.sorted() function
        stream.sorted().forEach(System.out::println);
    }
}

chevron_right


Output:

1279.6146863795122
6927.016817313592
7037.390703089559
8374.314582282514
9112.609381925824


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.