I want to create a function that builds an array of incremental numbers.
For example, I want to obtain something like:
int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, ..., 1000000};
The function will receive two parameters: start number (inclusive) and the final length of the array:
public int[] buildIncrementalArray(int start, int length) { ... }
I know how to do it using a for loop:
public int[] buildIncrementalArray(int start, int length) {
int[] result = new int[length];
for(int i = 0 ; i < length ; i++) {
result[i] = start + i;
}
return result;
}
Instead of using a for loop, I want to use Java 8 Stream API. Does anybody know how to do it using Stream API?
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
public static <T> Stream<T> getStream(T[] arr) { return Arrays. stream(arr); } where, T represents generic type. Example 1 : Arrays. stream() to convert string array to stream.
There is already a built-in method for that:
int[] array = IntStream.range(start, start + length).toArray();
IntStream.range
returns a sequential ordered IntStream
from the start (inclusive) to the end (exclusive) by an incremental step of 1.
If you want to include the end element, you can use IntStream.rangeClosed
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With