What is the toArray() method of the LongStream interface?
The toArray() method of the LongStream interface is used to create a long type array that consists of the elements in the stream. This method is a terminal/last operation in the stream pipeline.
Syntax
long[] toArray();
Parameters
This method has no parameters.
Return value
This method returns a long type array.
Code
import java.util.Arrays;import java.util.stream.LongStream;class Main {public static void main(String[] args) {LongStream longStream = LongStream.range(5, 10);long[] longArray = longStream.toArray();System.out.println("Converting the longStream to an array - " + Arrays.toString(longArray));}}
Explanation
- In lines 1 and 2, we import the
Arraysclass and theLongStreaminterface. - In line 6, we create a stream of
longvalues, using therange()method of theLongStreaminterface. - In line 7, we convert the stream to a
longarray, using thetoArray()method. - In line 8, we print the object array.