Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
public class PeekingIterator implements Iterator<T> {
private T next;
private Iterator<T> iter;

public PeekingIterator(Iterator<T> iterator) {
// initialize any member here.
iter = iterator;
next = iter.hasNext() ? iter.next() : null;
}

// Returns the next element in the iteration without advancing the iterator.
public T peek() {
return next;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public T next() {
int result = next;
next = iter.hasNext() ? iter.next() : null;
return result;
}

@Override
public boolean hasNext() {
return next != null || iter.hasNext();
}
}