Java String Array Iterator Example

Problem

Given the signature of the Java method below

public static Iterator iterateStrings(String... strings)

Provide implementation that iterates through each string in the order that they are provided but it skips null values

Solution

We implement the Iterable interface. We add a class member variable to store the list values in an array of strings. We override hasNext, next and remove methods. hasNext method keeps track of the current position in list as we iterate. next method was modified such that null values are skipped. remove method is kept intact. Here is the code

public static class MyClass implements Iterable 
{
	//Array of strings
	private String[] m_arr;

	//Constructor
	public MyClass(String[] arr) 
	{
		this.m_arr = arr;
	}

	@Override
	public Iterator iterator() 
	{
		Iterator it = new Iterator() 
		{
			//Keep track of current position
			private int indx = 0;

			@Override
			//True as long as there are more elements
			public boolean hasNext() 
			{
				return indx < m_arr.length;
			}

			@Override
			//Get next value but skip null values
			public String next() 
			{
				//No more values to get
				if (!hasNext()) return null;
				
				//Get none null value
				if (m_arr[indx++] != null)
				{
					return m_arr[indx-1];
				}
				//Skip null values
				else
				{
					return next();
				}	
			}
			
			@Override
			public void remove() 
			{
				//do nothing
			}  	            
		};
		
		return it;   	
	}
}

public static Iterator iterateStrings(String... strings) 
{
	//Wrap the string array in our custom built list
	MyClass list = new MyClass(strings);  	        	
	return list.iterator();
}

Leave a Reply

%d bloggers like this: