Java String Array of Iterators

Problem

Given the Java method signature below. It receives an array of string iterators. The method should return a single string iterator that chains all iterators in order skipping null values

public static Iterator iterateStrings(List<Iterator> stringIterators)

Solution

We wrap the array of iterators in a list that implements the iterable interface and override the hasNext, next and remove methods.

  • hasNext: it makes sure the current iterator is not null if it is null then there is no next item so it returns false otherwise it uses the current iterator hasNext method. It is kind of nesting, the outer hasNext uses the inner hasNext
  • next: this keeps looping as long as an individual iterator has elements. It checks for nulls as well and the moment there is no more elements in the current iterator it moves to the next iterator in the array
public static class MyClass implements Iterable 
{	 		
	//List of string iterators
	private List<Iterator> m_itrArr;

	//Construct list from a list of string iterators 
	public MyClass(List<Iterator> itrArr) 
	{
		this.m_itrArr = itrArr;
	}

	@Override
	public Iterator iterator() 
	{
		Iterator it = new Iterator() 
		{
			//Index of current string iterator
			private int itr_indx = 0;

			@Override
			public boolean hasNext() 
			{
				//Make sure the current iterator is not null
				//This check is a requirement in this problem
				if (m_itrArr.get(itr_indx) != null)
				{	
					//If the current iterator has next then
					//the chain iterator has next as well
					if (m_itrArr.get(itr_indx).hasNext())
					{
						return true;
					}
					//Otherwise I just use the next iterator
					//in the list of iterators. I also need
					//to make sure that we stop at the last
					//iterator
					else
					{
						if (itr_indx < m_itrArr.size()-1)
						{
							return m_itrArr.get(itr_indx+1).hasNext();
						}
						else
						{
							return false;
						}
					}
				}
				else
				{
					return false;
				}
			}

			@Override
			public String next() 
			{		 	            	
				//As long as the current iterator has 
				//elements that are not null get these elements
				while (m_itrArr.get(itr_indx).hasNext())
				{
					String str = m_itrArr.get(itr_indx).next();

					//Make sure the current string is not null
					//This check is a requirement in this problem
					if (str != null)
					{
						return str;
					}
					else
					{
						return next();
					}
				}
				
				//Move to the next iterator in the list
				itr_indx++;
				return next();
			}
			
			@Override
			public void remove() 
			{
				//do nothing
			}  	            
		};
		
		return it;   	
	}
}

public static Iterator iterateStrings(List<Iterator> stringIterators) 
{
	//Wrap the iterator array in our custom built list
	MyClass list = new MyClass(stringIterators);  	        	
	return list.iterator();
}

Tags:

Leave a Reply