1234567891011121314151617181920212223242526272829303132 |
- // Java Iterator interface reference:
- // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
- class PeekingIterator implements Iterator<Integer> {
- private Iterator<Integer> iter;
- private Integer peek;
- public PeekingIterator(Iterator<Integer> iterator) {
- // initialize any member here.
- this.iter = iterator;
- }
- // Returns the next element in the iteration without advancing the iterator.
- public Integer peek() {
- if (this.peek == null) this.peek = this.iter.next();
- return this.peek;
- }
- // hasNext() and next() should behave the same as in the Iterator interface.
- // Override them if needed.
- @Override
- public Integer next() {
- if (this.peek == null) return this.iter.next();
- Integer next = this.peek;
- this.peek = null;
- return next;
- }
- @Override
- public boolean hasNext() {
- return peek != null || this.iter.hasNext();
- }
- }
|