001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.util;
018
019import java.util.Iterator;
020import java.util.LinkedHashSet;
021import java.util.NoSuchElementException;
022import java.util.Set;
023
024/**
025 * Composite iterator that combines multiple other iterators,
026 * as registered via {@link #add(Iterator)}.
027 *
028 * <p>This implementation maintains a linked set of iterators
029 * which are invoked in sequence until all iterators are exhausted.
030 *
031 * @author Erwin Vervaet
032 * @author Juergen Hoeller
033 * @since 3.0
034 * @param <E> the element type
035 */
036public class CompositeIterator<E> implements Iterator<E> {
037
038        private final Set<Iterator<E>> iterators = new LinkedHashSet<>();
039
040        private boolean inUse = false;
041
042
043        /**
044         * Add given iterator to this composite.
045         */
046        public void add(Iterator<E> iterator) {
047                Assert.state(!this.inUse, "You can no longer add iterators to a composite iterator that's already in use");
048                if (this.iterators.contains(iterator)) {
049                        throw new IllegalArgumentException("You cannot add the same iterator twice");
050                }
051                this.iterators.add(iterator);
052        }
053
054        @Override
055        public boolean hasNext() {
056                this.inUse = true;
057                for (Iterator<E> iterator : this.iterators) {
058                        if (iterator.hasNext()) {
059                                return true;
060                        }
061                }
062                return false;
063        }
064
065        @Override
066        public E next() {
067                this.inUse = true;
068                for (Iterator<E> iterator : this.iterators) {
069                        if (iterator.hasNext()) {
070                                return iterator.next();
071                        }
072                }
073                throw new NoSuchElementException("All iterators exhausted");
074        }
075
076        @Override
077        public void remove() {
078                throw new UnsupportedOperationException("CompositeIterator does not support remove()");
079        }
080
081}