Create array of incremental int using Stream instead of for loop

别来无恙 提交于 2020-07-29 06:14:11

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

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


来源:https://stackoverflow.com/questions/32823338/create-array-of-incremental-int-using-stream-instead-of-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!