How to populate a Java int array with a range of values

As a quick note, here’s an easy way to populate a Java int array with initial data, such as an initial range of numbers. The key is to use the rangeClosed method on the Java 8 IntStream class. Here’s an example using the Scala REPL:

scala> val n = java.util.stream.IntStream.rangeClosed(0, 10).toArray()
n: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

I show that in Scala so I can easily show the output, and here’s what it looks like with Java:

int[] nums = java.util.stream.IntStream.rangeClosed(0, 10).toArray()

For more information see the IntStream Javadoc.