001/* 002 * Copyright 2002-2014 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 */ 035public class CompositeIterator<E> implements Iterator<E> { 036 037 private final Set<Iterator<E>> iterators = new LinkedHashSet<Iterator<E>>(); 038 039 private boolean inUse = false; 040 041 042 /** 043 * Add given iterator to this composite. 044 */ 045 public void add(Iterator<E> iterator) { 046 Assert.state(!this.inUse, "You can no longer add iterators to a composite iterator that's already in use"); 047 if (this.iterators.contains(iterator)) { 048 throw new IllegalArgumentException("You cannot add the same iterator twice"); 049 } 050 this.iterators.add(iterator); 051 } 052 053 @Override 054 public boolean hasNext() { 055 this.inUse = true; 056 for (Iterator<E> iterator : this.iterators) { 057 if (iterator.hasNext()) { 058 return true; 059 } 060 } 061 return false; 062 } 063 064 @Override 065 public E next() { 066 this.inUse = true; 067 for (Iterator<E> iterator : this.iterators) { 068 if (iterator.hasNext()) { 069 return iterator.next(); 070 } 071 } 072 throw new NoSuchElementException("All iterators exhausted"); 073 } 074 075 @Override 076 public void remove() { 077 throw new UnsupportedOperationException("CompositeIterator does not support remove()"); 078 } 079 080}