4

Any shortcut to create a Java array of the first n integers without doing an explicit loop? In R, it would be

intArray = c(1:n) 

(and the resulting vector would be 1,2,...,n).

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
bigO6377
  • 1,256
  • 3
  • 14
  • 28
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3790142/java-equivalent-of-pythons-rangeint-int. – Roberto Reale Apr 17 '14 at 19:57
  • http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(float[], int, int) – kosa Apr 17 '14 at 19:58
  • You said "array" and "vector", which are 2 different things in Java and the simplest way to do this is different for each of those. Do you know which you want? – Jeff Scott Brown Apr 17 '14 at 19:58

1 Answers1

16

If you're using , you could do:

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

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

If you want to specify a step, you could iterate and then limit the stream to take the first n elements you want.

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

Otherwise I guess the simplest way to do is to use a loop and fill the array. You can create a helper method if you want.

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]

You can adapt this method as your needs to go per example from an upperbound to a lowerbound with a negative step.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177