Merge list of Iterators into a single Iterator using Google Guava collection framework

It is one of advanced level java interview questions- Device an algorithm to merge list of Iterators into a single Iterator. Google guava provides collections framework which does it in couple of lines.

Below lines shows how to merge multiple iterators and provide single iterator out of it.

Iterable<Integer> iterable = Iterables.concat(list1, list2,list3, list4);
Iterator<Integer> iterator = iterable.iterator();

Sample program demonstrating above concept

package javacore;

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

import com.google.common.collect.Iterables;

public class IteratorOverAlIteratorsGuava {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Iterator<Integer> iterator = iterators();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 }

 public static Iterator<Integer> iterators() {
  List<Integer> list1 = new ArrayList<>();
  list1.add(0);
  list1.add(1);
  list1.add(2);
  List<Integer> list2 = Arrays.asList(3, 4);
  List<Integer> list3 = new ArrayList<>();
  List<Integer> list4 = Arrays.asList(5, 6, 7, 8, 9);

  final Iterable<Integer> iterable = Iterables.concat(list1, list2,
    list3, list4);
  final Iterator<Integer> iterator = iterable.iterator();
  return iterator;
 }
}

Sample Output:-
0
1
2
3
4
5
6
7
8
9

1 Comments

Previous Post Next Post