#110 Merging Multiple Iterators

Companies:
Sportmaster
Themes:
JavaCollections & GenericsPractice

Two iterators are given.

  • Implement an iterator that can merge the two given iterators: it returns all elements from the first iterator and then all elements from the second.
  • Do the same when the number of iterators may be arbitrary.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> strings1 = new ArrayList<>();
        List<String> strings2 = new ArrayList<>();

        strings1.add("1");
        strings1.add("2");
        strings1.add("3");
        Iterator<String> iterator1 = strings1.iterator();

        strings2.add("9");
        strings2.add("8");
        strings2.add("7");
        Iterator<String> iterator2 = strings2.iterator();

        List<Iterator<String>> listIterator = new ArrayList<>();
        listIterator.add(iterator1);
        listIterator.add(iterator2);

//        var newIterator = new NewIterator((Iterator<String>) iterator1, (Iterator<String>) iterator2);
//
//        while (newIterator.hasNext()){
//            System.out.println(newIterator.next());
//        }

        var newIterator = new NewIteratorList(listIterator);

        while (newIterator.hasNext()){
            System.out.println(newIterator.next());
        }
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in