001/* 002 * ModeShape (http://www.modeshape.org) 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 * http://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 */ 016package org.modeshape.common.collection; 017 018import java.util.Iterator; 019 020/** 021 * An iterator that abstracts iterating over two other iterators. 022 * 023 * @param <T> the type 024 * @author Randall Hauch (rhauch@redhat.com) 025 */ 026public class SequentialIterator<T> implements Iterator<T> { 027 028 public static <T> SequentialIterator<T> create( Iterator<T> first, 029 Iterator<T> second ) { 030 return new SequentialIterator<T>(first, second); 031 } 032 033 private final Iterator<T> first; 034 private final Iterator<T> second; 035 private boolean completedFirst = false; 036 037 public SequentialIterator( Iterator<T> first, 038 Iterator<T> second ) { 039 this.first = first; 040 this.second = second; 041 } 042 043 @Override 044 public boolean hasNext() { 045 if (!completedFirst) { 046 if (first.hasNext()) return true; 047 completedFirst = true; 048 } 049 return second.hasNext(); 050 } 051 052 @Override 053 public T next() { 054 if (!completedFirst) { 055 if (first.hasNext()) return first.next(); 056 completedFirst = true; 057 } 058 return second.next(); 059 } 060 061 @Override 062 public void remove() { 063 if (!completedFirst) { 064 first.remove(); 065 } 066 second.remove(); 067 } 068 069}