What is the toArray() method of the IntStream interface?

The IntStream interface’s toArray() method creates an integer array consisting of the elements in the stream. This method is a terminal/last operation in the stream pipeline.

Syntax

int[] toArray();

Parameters

The method has no parameters.

Return value

The method returns an integer array.

Code

import java.util.Arrays;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
IntStream intStream = IntStream.range(5, 10);
int[] intArray = intStream.toArray();
System.out.println("Converting the IntStream to an array - " + Arrays.toString(intArray));
}
}

Explanation

  • Lines 1 and 2: We import the Arrays class and the IntStream interface.
  • Line 6: We create a stream of integers using the range() method of the IntStream interface.
  • Line 7: We convert the stream to an integer array using the toArray() method.
  • Line 8: We print the integer array.

Free Resources