#110 Merging Multiple Iterators
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor