shortest way of filling an array with 1,2...n

Since Java 8 this is possible:

int[] a = IntStream.range(1, 100).toArray();

(And shorter than the other java 8 answer .).


Java 8 allows to do that in one line with IntStream object and lambda expression:

int n = 10;
int[] values = new int[n];
IntStream.range(1,n+1).forEach(val -> values[val-1] = val);

Another alternative if you use Java 8:

int[] array = new int[100];
Arrays.setAll(array, i -> i + 1);

The lambda expression accepts the index of the cell, and returns a value to put in that cell. In this case, cells 0 - 99 are assigned the values 1-100.

Tags:

Java

Arrays