Peeking Iterator

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().

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint:

  1. Think of “looking ahead”. You want to cache the next element.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek() before next() vs next() before peek().
  4. For a clean implementation, check out Google’s guava library source code.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Solution:

  1. // Java Iterator interface reference:
  2. // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
  3. class PeekingIterator implements Iterator<Integer> {
  4. Integer num;
  5. Iterator<Integer> iterator;
  6. public PeekingIterator(Iterator<Integer> iterator) {
  7. // initialize any member here.
  8. this.num = null;
  9. this.iterator = iterator;
  10. }
  11. // Returns the next element in the iteration without advancing the iterator.
  12. public Integer peek() {
  13. if (num == null && iterator.hasNext()) {
  14. num = iterator.next();
  15. }
  16. return num;
  17. }
  18. // hasNext() and next() should behave the same as in the Iterator interface.
  19. // Override them if needed.
  20. @Override
  21. public Integer next() {
  22. if (num == null) {
  23. return iterator.next();
  24. }
  25. Integer tmp = num;
  26. num = null;
  27. return tmp;
  28. }
  29. @Override
  30. public boolean hasNext() {
  31. return num != null || iterator.hasNext();
  32. }
  33. }