Is there a short and sweet way to generate a List
, or perhaps an Integer[]
or int[]
, with sequential values from some
This is the shortest I could get using Core Java.
List<Integer> makeSequence(int begin, int end) {
List<Integer> ret = new ArrayList(end - begin + 1);
for(int i = begin; i <= end; i++, ret.add(i));
return ret;
}
This one might works for you....
void List<Integer> makeSequence(int begin, int end) {
AtomicInteger ai=new AtomicInteger(begin);
List<Integer> ret = new ArrayList(end-begin+1);
while ( end-->begin) {
ret.add(ai.getAndIncrement());
}
return ret;
}
With Java 8 it is so simple so it doesn't even need separate method anymore:
List<Integer> range = IntStream.rangeClosed(start, end)
.boxed().collect(Collectors.toList());
This is the shortest I could find.
List version
public List<Integer> makeSequence(int begin, int end)
{
List<Integer> ret = new ArrayList<Integer>(++end - begin);
for (; begin < end; )
ret.add(begin++);
return ret;
}
Array Version
public int[] makeSequence(int begin, int end)
{
if(end < begin)
return null;
int[] ret = new int[++end - begin];
for (int i=0; begin < end; )
ret[i++] = begin++;
return ret;
}
Well, this one liner might qualify (uses Guava Ranges)
ContiguousSet<Integer> integerList = ContiguousSet.create(Range.closedOpen(0, 10), DiscreteDomain.integers());
System.out.println(integerList);
This doesn't create a List<Integer>
, but ContiguousSet
offers much the same functionality, in particular implementing Iterable<Integer>
which allows foreach
implementation in the same way as List<Integer>
.
In older versions (somewhere before Guava 14) you could use this:
ImmutableList<Integer> integerList = Ranges.closedOpen(0, 10).asSet(DiscreteDomains.integers()).asList();
System.out.println(integerList);
Both produce:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The following one-liner Java 8 version will generate [ 1, 2 ,3 ... 10 ]. The first arg of iterate
is the first nr in the sequence, and the first arg of limit
is the last number.
List<Integer> numbers = Stream.iterate(1, n -> n + 1)
.limit(10)
.collect(Collectors.toList());