package com.github.nikita_volkov.java.iterators;

import java.util.*;

public final class MultimapIterator<key, value> implements Iterator<MultimapIterator.Entry> {

  private final Iterator<Map.Entry<key, Iterable<value>>> iterator;
  private key currentKey;
  private Iterator<value> currentDeeperIterator;

  public MultimapIterator(Map<key, Iterable<value>> map) {
    iterator = map.entrySet().iterator();
    fetchNextEntry();
  }

  private void fetchNextEntry() {
    if (iterator.hasNext()) {
      Map.Entry<key, Iterable<value>> entry = iterator.next();
      currentDeeperIterator = entry.getValue().iterator();
      if (!currentDeeperIterator.hasNext()) {
        fetchNextEntry();
        return;
      }
      currentKey = entry.getKey();
    }
  }

  @Override
  public boolean hasNext() {
    return currentDeeperIterator.hasNext();
  }

  @Override
  public Entry next() {
    key key = currentKey;
    value value = currentDeeperIterator.next();
    fetchNextEntry();
    return new Entry(key, value);
  }

  public final class Entry {
    public final key key;
    public final value value;

    private Entry(key key, value value) {
      this.key = key;
      this.value = value;
    }
  }

}

@@ -110,16 +110,55 @@
 y, value
+, valueIterable extends Iterable%3Cvalue%3E
 %3E implem
@@ -193,16 +193,28 @@
 or.Entry
+%3Ckey, value%3E
 %3E %7B%0A%0A  p
@@ -246,32 +246,37 @@
 .Entry%3Ckey, 
+value
 Iterable
 %3Cvalue%3E%3E%3E it
@@ -263,23 +263,16 @@
 Iterable
-%3Cvalue%3E
 %3E%3E itera
@@ -383,32 +383,37 @@
 or(Map%3Ckey, 
+value
 Iterable
 %3Cvalue%3E%3E map
@@ -400,23 +400,16 @@
 Iterable
-%3Cvalue%3E
 %3E map) %7B
@@ -563,24 +563,29 @@
 ry%3Ckey, 
+value
 Iterable
 %3Cvalue%3E%3E
@@ -576,23 +576,16 @@
 Iterable
-%3Cvalue%3E
 %3E entry 
@@ -920,16 +920,28 @@
 ic Entry
+%3Ckey, value%3E
  next() 
@@ -1054,24 +1054,26 @@
 rn new Entry
+%3C%3E
 (key, value)
@@ -1090,24 +1090,31 @@
 ublic final 
+static 
 class Entry 
@@ -1112,16 +1112,28 @@
 ss Entry
+%3Ckey, value%3E
  %7B%0A    p

Update MultimapIterator