code: public static <T> CloseableIterator<T> autoClose(final CloseableIterator<? extends T> iterator) {
          requireNonNull(iterator);
          return new CloseableIterator<T>() {
              private boolean closed = false;
  
              @Override
              public void close() {
                  if (closed)
                      return;
  
                  closed = true;
                  iterator.close();
              }
  
              @Override
              public boolean hasNext() {
                  try {
                      if (closed)
                          return false;
                      if (!iterator.hasNext()) {
                          closeQuietly();
                          return false;
                      }
                      return true;
                  } catch (RuntimeException re) {
                      closeQuietly();
                      throw re;
                  }
              }
  
              @Override
              public T next() {
                  if (!closed) {
                      try {
                          return iterator.next();
                      } catch (RuntimeException re) {
                          closeQuietly();
                          throw re;
                      }
                  }
                  throw new NoSuchElementException();
              }
  
              @Override
              public void remove() {
                  if (!closed) {
                      try {
                          iterator.remove();
                      } catch (RuntimeException re) {
                          closeQuietly();
                          throw re;
                      }
                  }
                  throw new IllegalStateException();
              }
          };
      }
docs: Autoclose the iterator when exhausted or if an exception is thrown.
  <p/>
  Note that when using this method the order of calls matters. {@code limit()} is an example of one method which can
  prevent the completion of an iterator.  For instance limit(autoClose(iterator), 1) will not close the
  resource if there is more than 1 element, but autoClose(limit(iterator, 1)) will close the underlying
  resource.