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 Arrays class and the LongStream interface.
  • In line 6, we create a stream of long values, using the range() method of the LongStream interface.
  • In line 7, we convert the stream to a long array, using the toArray() method.
  • In line 8, we print the object array.

Free Resources