Java String Array of Iterators

Problem

Given the Java method signature below. It receives an array of string iterators. The method should return a single string iterator that chains all iterators in order skipping null values

Solution

We wrap the array of iterators in a list that implements the iterable interface and override the hasNext, next and remove methods.

  • hasNext: it makes sure the current iterator is not null if it is null then there is no next item so it returns false otherwise it uses the current iterator hasNext method. It is kind of nesting, the outer hasNext uses the inner hasNext
  • next: this keeps looping as long as an individual iterator has elements. It checks for nulls as well and the moment there is no more elements in the current iterator it moves to the next iterator in the array

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *