jfcorugedo
jfcorugedo

Reputation: 10061

Create array of incremental int using Stream instead of for loop

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?

Upvotes: 9

Views: 5998

Answers (3)

Arnab Banerjee
Arnab Banerjee

Reputation: 51

If you find for light code then you may use this one

int[] myArray = new int[n];
while(n-- >= 0){
    myArray[n] = n+1;
}

Upvotes: 0

Vishal Zanzrukia
Vishal Zanzrukia

Reputation: 4973

You can try in this way using IntStream,

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

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

Upvotes: 0

Tunaki
Tunaki

Reputation: 137209

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.

Upvotes: 20

Related Questions