Copied from AbstractCollection since we need to close iterator
199660
@Override
   public Object[] toArray() {
      // Estimate size of array; be prepared to see more or fewer elements
      Object[] r = new Object[size()];
      try (CloseableIterator<O> it = iterator()) {
         for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) // fewer elements than expected
               return Arrays.copyOf(r, i);
            r[i] = it.next();
         }
         return it.hasNext() ? finishToArray(r, it) : r;
      }
   }
793723
void close() throws RepositoryException {
        mLock.lock();
        if (mClosed) {
            mLock.unlock();
            return;
        }
 
        Map<Class<?>, CursorList<TransactionImpl<Txn>>> cursors;
        try {
            cursors = mCursors;        

            // Ensure that map is freed promptly. Thread-local reference to
            // this scope otherwise keeps map and its contents lingering around
            // for a very long time.
            mCursors = null;

            while (mActive != null) {
                mActive.exit();
            }
        } finally {
            // Swap TransactionManager out with a dummy one, to allow the
            // original one to get freed.
            mTxnMgr = (TransactionManager<Txn>) TransactionManager.Closed.THE;
            mClosed = true;
            mLock.unlock();
        }

        // Close cursors without lock held, to prevent deadlock. Cursor close
        // operation might acquire its own lock, which in turn acquires a lock
        // on this scope.
        if (cursors != null) {
            for (CursorList<TransactionImpl<Txn>> cursorList : cursors.values()) {
                cursorList.closeCursors();
            }
        }
    }
991267
public static <T> boolean removeAllIterable(Iterable<? extends T> iterable, Collection<T> targetCollection)
    {
        if (iterable == null)
        {
            throw new NullPointerException();
        }
        if (iterable instanceof Collection<?>)
        {
            return targetCollection.removeAll((Collection<T>) iterable);
        }
        int oldSize = targetCollection.size();
        Iterate.forEachWith(iterable, Procedures2.<T>removeFromCollection(), targetCollection);
        return targetCollection.size() != oldSize;
    }
85360
protected void writeCollectionValue(Collection<?> v) throws IOException
    {
        _generator.writeStartArray();
        for (Object ob : v) {
            writeValue(ob);
        }
        _generator.writeEndArray();
    }
15877
function each(collection, iterator) {
  for (var i = 0; i < collection.length; i++) {
    iterator(collection[i], i);
  }
}
18553
@Override
    public void close()
    {
        isOpen.set(false);
        Iterator<Future<?>> iterator = futures.iterator();
        while ( iterator.hasNext() )
        {
            Future<?> future = iterator.next();
            iterator.remove();
            if ( !future.isDone() && !future.isCancelled() && !future.cancel(true) )
            {
                log.warn("Could not cancel " + future);
            }
        }
        if (shutdownOnClose) {
            executorService.shutdownNow();
        }
    }
658623
private void endCollectionLoad(
			final ResultSet resultSetId,
			final SharedSessionContractImplementor session,
			final CollectionPersister collectionPersister) {
		//this is a query and we are loading multiple instances of the same collection role
		session.getPersistenceContext()
				.getLoadContexts()
				.getCollectionLoadContext( resultSetId )
				//.getCollectionLoadContext( ( ResultSet ) resultSetId )
				.endLoadingCollections( collectionPersister );
	}
1046299
@Override
   public Iterator<R> iterator() {
      log.tracef("Distributed iterator invoked with rehash: %s", rehashAware);
      if (!rehashAware) {
         // Non rehash doesn't care about lost segments or completed ones
         CloseableIterator<R> closeableIterator = nonRehashRemoteIterator(dm.getReadConsistentHash(), segmentsToFilter,
               null, IdentityPublisherDecorator.getInstance(), intermediateOperations);
         onClose(closeableIterator::close);
         return closeableIterator;
      } else {
         Iterable<IntermediateOperation> ops = iteratorOperation.prepareForIteration(intermediateOperations,
               (Function) nonNullKeyFunction());
         CloseableIterator<R> closeableIterator;
         if (segmentCompletionListener != null && iteratorOperation != IteratorOperation.FLAT_MAP) {
            closeableIterator = new CompletionListenerRehashIterator<>(ops, segmentCompletionListener);
         } else {
            closeableIterator = new RehashIterator<>(ops);
         }
         onClose(closeableIterator::close);
         // This cast messes up generic checking, but that is okay
         Function<R, R> function = iteratorOperation.getFunction();
         if (function != null) {
            return new IteratorMapper<>(closeableIterator, function);
         } else {
            return closeableIterator;
         }
      }
   }
494570
public boolean removeAll(Collection<?> collection) {
        boolean result = false;
        synchronized (mLock) {
            Iterator<?> it;
            if (mOriginalValues != null) {
                it = mOriginalValues.iterator();

            } else {
                it = mObjects.iterator();
            }
            while (it.hasNext()) {
                if (collection.contains(it.next())) {
                    it.remove();
                    result = true;
                }
            }
        }
        if (mNotifyOnChange) notifyDataSetChanged();
        return result;
    }
117039
@Override
    public void close() throws Exception {
        if (scopeCleaner.close()) { // executor thread to exit processing loop            
            LOGGER.info("closing PreDestroyMonitor...");
            List<Map.Entry<Object, UnscopedCleanupAction>> actions = new ArrayList<>(cleanupActions.entrySet());
            if (actions.size() > 0) {
                LOGGER.warn("invoking predestroy action for {} unscoped instances", actions.size());
                actions.stream().map(Map.Entry::getValue).collect(
                    Collectors.groupingBy(UnscopedCleanupAction::getContext, Collectors.counting())).forEach((source, count)->{
                        LOGGER.warn("  including {} objects from source '{}'", count, source);
                    });
            }
            actions.stream().sorted(Map.Entry.comparingByValue()).forEach(action->{
                Optional.ofNullable(action.getKey()).ifPresent(obj->action.getValue().call(obj));                    
            });             
            actions.clear();
            cleanupActions.clear();
            scopeBindings.clear();
            scopeBindings = Collections.emptyMap();
        } else {
            LOGGER.warn("PreDestroyMonitor.close() invoked but instance is not running");
        }
    }
181837
public static <T> Collection<T> immutableCollectionCopy(Collection<T> collection) {
      if (collection == null) return null;
      if (collection.isEmpty()) return Collections.emptySet();
      if (collection.size() == 1) return Collections.singleton(collection.iterator().next());

      Collection<? extends T> copy = ObjectDuplicator.duplicateCollection(collection);
      if (copy == null)
         copy = attemptCopyConstructor(collection, Collection.class);
      if (copy == null)
         copy = new ArrayList<>(collection);

      return new ImmutableCollectionWrapper<>(copy);
   }
1052999
public static <T, C extends Collection<? super T>> C toCollection(
        Iterator<T> iterator, C collection)
    {
        Objects.requireNonNull(iterator, "The iterator is null");
        Objects.requireNonNull(iterator, "The collection is null");
        while (iterator.hasNext())
        {
            collection.add(iterator.next());
        }
        return collection;
    }
287584
protected static void writeIterator(Output out, Iterator<Object> it) {
        log.trace("writeIterator");
        // Create LinkedList of collection we iterate thru and write it out later
        LinkedList<Object> list = new LinkedList<Object>();
        while (it.hasNext()) {
            list.addLast(it.next());
        }
        // Write out collection
        out.writeArray(list);
    }
40006
public static <T> boolean removeIf(Iterable<T> iterable, Predicate<? super T> predicate)
    {
        if (iterable instanceof MutableCollection)
        {
            return ((MutableCollection<T>) iterable).removeIf(predicate);
        }
        if (iterable instanceof ArrayList)
        {
            return ArrayListIterate.removeIf((ArrayList<T>) iterable, predicate);
        }
        if (iterable instanceof List)
        {
            return ListIterate.removeIf((List<T>) iterable, predicate);
        }
        if (iterable != null)
        {
            return IterableIterate.removeIf(iterable, predicate);
        }
        throw new IllegalArgumentException("Cannot perform a remove on null");
    }
789572
public static <T> CloseableIterator<T> distinct(final CloseableIterator<T> iterator) {
        return wrap(Iterators2.distinct(iterator), iterator);
    }
543740
public static <T> Source<T> join(final Iterator<Source<T>> iterator) {
        return new AbstractSource<T>() {
            private Source<T> current = popSource();

            @Override
            public T computeNext() throws IOException {
                while (current != null) {
                    if (current.hasNext()) {
                        return current.next();
                    } else {
                        current.close();
                        current = popSource();
                    }
                }
                return endOfData();
            }

            @Override
            public void close() {
                while (current != null) {
                    current.close();
                    current = popSource();
                }
            }

            private Source<T> popSource() {
                if (iterator.hasNext()) {
                    return iterator.next();
                } else {
                    return null;
                }
            }
        };
    }
174615
public void dispose(){
		Collection pageComponents = new ArrayList(pageComponentMap.values());
		Iterator it = pageComponents.iterator();
		while(it.hasNext()){
			PageComponent pageComponent = (PageComponent)it.next();
			remove(pageComponent);
		}
		contentPane.dispose();
		contentPane = null;
		super.dispose();
	}