Is there any syntax/package allowing quick filling of java arrays with ranges of numbers, like in perl?
e.g.
int[] arr = new int[1000]; arr=(1..500,301..400,1001..1400); // returns [1,2,3,4,...,500,301,302,...,400,1001,1002,...1400]
Also, it here a package that allows getting the n-th number in such list of numbers as the above, without actually creating the array (which can be huge)?
e.g.
BunchOfRangesType bort = new BunchOfRangesType("1..500","301..400","1001..1400"); bort.get(0); // return 1 bort.get(500); // return 301 bort.get(501); // return 302
It's not too difficult to implement, but I guess it might be common so maybe it was already done.
the Array. map() function is used to create a new array with a modified range of numbers. the Math. floor() function rounds a number down to the nearest integer, it's used in the last example to ensure a whole number is passed to the Array() function regardless of the step size.
Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.
For those still looking for a solution:
In Java 8 or later, this can be answered trivially using Streams without any loops or additional libraries.
int[] range = IntStream.rangeClosed(1, 10).toArray();
This will produce an array with the integers from 1 to 10.
A more general solution that produces the same result is below. This can be made to produce any sequence by modifying the unary operator.
int[] range = IntStream.iterate(1, n -> n + 1).limit(10).toArray();
There is dollar:
// build the List 10, 11, 12, 13, 14 List<Integer> list2 = $(10, 15).toList();
maven:
<dependency> <groupId>org.bitbucket.dollar</groupId> <artifactId>dollar</artifactId> <version>1.0-beta3</version> </dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With