Fill arrays with ranges of numbers
Solution 1:
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();
Solution 2:
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>
Solution 3:
Another useful and not widely known Java 8 solution for existing arrays:
int[] array = new int[10];
Arrays.setAll(array, i -> i + 1);
Solution 4:
As for the first question, whether it is possible to fill an array with the values of a range: it is actually possible to achieve that with the combination of Range, DiscreteDomain, ContiguousSet and Ints from Guava:
int[] array = Ints.toArray(
ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers()));
And, not exactly what is mentioned in the second part of the question, but it is possible to create a set with the elements of a range of a discrete domain:
Set<Integer> numbersFrom1To500 =
ContiguousSet.create(Range.closed(1, 500), DiscreteDomain.integers());
The resulting Set
will not contain the specified elements physically, only logically (so it's memory footprint will be small), but can be iterated (since it's a Set
):
for (Integer integer : numbersFrom1To500) {
System.out.println(integer);
}
Solution 5:
Not quite as clean as True Soft's answer, but you can use Google Guava to the same effect:
public class Test {
public static void main(String[] args) {
//one liner
int[] array = toArray(newLinkedList(concat(range(1, 10), range(500, 1000))));
//more readable
Iterable<Integer> values = concat(range(1, 10), range(500, 1000));
List<Integer> list = newLinkedList(values);
int[] array = toArray(list);
}
public static List<Integer> range(int min, int max) {
List<Integer> list = newLinkedList();
for (int i = min; i <= max; i++) {
list.add(i);
}
return list;
}
}
Note you need a few static imports for this to work.