cretzel cretzel - 2 months ago 9
Java Question

Shortest way to get an Iterator over a range of Integers in Java

What's the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:

/**
* Returns an Iterator over the integers from first to first+count.
*/
Iterator<Integer> iterator(Integer first, Integer count);


Something like

(first..first+count).iterator()

Answer

Straight-forward implementation of your homework:

List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
    ints.add(first + i);
}