Create an incremental int array using Stream instead of loop

I want to create a function that builds an array of incremental numbers.

For example, I want to get something like:

int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, ..., 1000000}; 

The function will receive two parameters: the initial number (inclusive) and the final length of the array:

 public int[] buildIncrementalArray(int start, int length) { ... } 

I know how to do this 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 the Java 8 Stream API. Does anyone know how to do this using the Stream API?

+6
source share
2 answers

There is already a built-in method for this:

 int[] array = IntStream.range(start, start + length).toArray(); 

IntStream.range returns a sequentially ordered IntStream from the beginning (inclusive) to the end (exclusive) in increments of 1.

If you want to include the final element, you can use IntStream.rangeClosed .

+14
source

You can try this way using IntStream ,

 int[] array = new int[length]; IntStream.range(0, length).forEach(i -> array[i] = i + 1); 

Please let me know if this does not work for you.

-1
source

All Articles