May 22, 2017

Write an algorithm that collapses a list of Iterators into a single Iterator - Java Program

Write an algorithm that collapses a list of Iterators into a single Iterator. 

package javacore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollapseIterators {
 /**
  * @param args
  *            Write an algorithm that collapses a list of Iterators into a
  *            single Iterator.
  */
 public static void main(String[] args) {
  final Iterator<Integer> a = Arrays.asList(1, 2, 3, 4, 5).iterator();
  final Iterator<Integer> b = Arrays.asList(6).iterator();
  final Iterator<Integer> c = new ArrayList<Integer>().iterator();
  final Iterator<Integer> d = new ArrayList<Integer>().iterator();
  final Iterator<Integer> e = Arrays.asList(7, 8, 9).iterator();

  final Iterator<Integer> singleIterator = singleIterator(Arrays.asList(
    a, b, c, d, e));
  if (null != singleIterator && singleIterator.hasNext()) {
   System.out.println("Single Iterator obtained!!");
   while (singleIterator.hasNext()) {
    System.out.println(singleIterator.next().toString());
   }
  } else {
   System.out.println("Single Iterator did not obtained");
  }
 }

 public static <T> Iterator<T> singleIterator(
   final List<Iterator<T>> iteratorList) {
  ListIterator<T> it = new ListIterator<>(iteratorList);
  return it;

 }
}

class ListIterator<T> implements Iterator<T> {
 // Field
 private final Iterator<Iterator<T>> listIterator;
 private Iterator<T> currentIterator;

 // Constructor: make list iterator into Iterator<iterator>>
 public ListIterator(List<Iterator<T>> iterators) {
  this.listIterator = iterators.iterator();
  this.currentIterator = listIterator.next();
 }

 @Override
 public boolean hasNext() {
  // CurrentIterator has no next
  if (!currentIterator.hasNext()) {
   // set up next iterator as currentIterator
   if (!listIterator.hasNext())
    return false;
   currentIterator = listIterator.next();
   // NOTE: recurse to check if next still has no next
   hasNext();
  }

  return true;

 }

 public T next() {
  hasNext();
  return currentIterator.next();
 }

 // public boolean remove()
 public void remove() {
  hasNext();
  currentIterator.remove();
 }
}

Sample Output:-
 
Single Iterator obtained!!
1
2
3
4
5
6
7
8
9

Problem reference: "Java Programming Interviews Exposed"

Related Question:
How can we achieve this behaviour using Google Guava collections framework ?
Location: Hyderabad, Telangana, India