Java: an array of the first n integers

Any shortcut to create a Java array from the first n integers without executing an explicit loop? In R, it will be

intArray = c(1:n) 

(and the resulting vector will be equal to 1,2, ..., n).

+4
source share
1 answer

If you are using java-8 , you can do:

int[] arr = IntStream.range(1, n).toArray();

This will create an array containing integers from [0, n). You can use rangeClosedif you want to include nin the resulting array.

If you want to specify a step, you can iterateand then limitstream to take the first nelements that you want.

int[] arr = IntStream.iterate(0, i ->i + 2).limit(10).toArray(); //[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

, , - . , .

static int[] fillArray(int from, int to, int step){
    if(to < from || step <= 0)
        throw new IllegalArgumentException("to < from or step <= 0");

    int[] array = new int[(to-from)/step+1];
    for(int i = 0; i < array.length; i++){
        array[i] = from;
        from += step;
    }
    return array;
}
...
int[] arr3 = fillArray(0, 10, 3); //[0, 3, 6, 9]

, .

+13

Source: https://habr.com/ru/post/1537008/


All Articles