Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

iterator

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()
like image 318
cretzel Avatar asked Aug 31 '25 18:08

cretzel


2 Answers

This implementation does not have a memory footprint.

/**
 * @param begin inclusive
 * @param end exclusive
 * @return list of integers from begin to end
 */
public static List<Integer> range(final int begin, final int end) {
    return new AbstractList<Integer>() {
            @Override
            public Integer get(int index) {
                return begin + index;
            }

            @Override
            public int size() {
                return end - begin;
            }
        };
}

Edit:

In Java 8 and later you can simply say:

IntStream.range(begin, end).iterator()          // returns PrimitiveIterator.OfInt

or if you need the boxed version:

IntStream.range(begin, end).boxed().iterator()  // returns Iterator<Integer>
like image 121
Saintali Avatar answered Sep 02 '25 09:09

Saintali


Untested. Mapping that onto "min, count" is left as an exercise for the reader.

public class IntRangeIterator implements Iterator<Integer> {
  private int nextValue;
  private final int max;
  public IntRangeIterator(int min, int max) {
    if (min > max) {
      throw new IllegalArgumentException("min must be <= max");
    }
    this.nextValue = min;
    this.max = max;
  }

  public boolean hasNext() {
    return nextValue <= max;
  }

  public Integer next() {
    if (!hasNext()) {
      throw new NoSuchElementException();
    }
    return Integer.valueOf(nextValue++);
  }

  public void remove() {
    throw new UnsupportedOperationException();
  }
}
like image 33
Joachim Sauer Avatar answered Sep 02 '25 07:09

Joachim Sauer