Nov 27, 2016

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

Location: Hyderabad, Telangana, India

2 comments:

  1. Spending some quality experiences in the arms of the busty girls is truly unique.Cheap Escorts Service in Mahipalpur Feel the heat of the models often and have fun with their curvy bodies.Call Girls near Dehradun Bus Stand Relishing great entertainment with these girls could make you feel better than ever.Call Girls near Dehradun Bus Stand Simply hire the right partner and make love with her passionately.Bengali Call Girls in Agra The close companionship that you can make with the sizzling girl would be spectacular.Bengali Call Girls in Agra So, ensure to do all types of hot moves and feel the heat of the beautiful companions.Bengali Call Girls in Ajmer Feel the heat of the body of the dazzling girl and make love with her figure passionately.

    ReplyDelete