Skip to content

Instantly share code, notes, and snippets.

@amitsaurav
Created November 23, 2016 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaurav/2673b33729b871c4cb7d28eeab583b8b to your computer and use it in GitHub Desktop.
Save amitsaurav/2673b33729b871c4cb7d28eeab583b8b to your computer and use it in GitHub Desktop.
List of Lists iterator.
package collections;
import java.util.Arrays;
import java.util.List;
/**
* Created by amit.saurav on 11/23/16.
*/
public class ListOfLists <T> {
private final List<List<T>> listOfLists;
private int currentRow;
private int currentCol;
public ListOfLists(List<List<T>> lists) {
listOfLists = lists;
resetIterator();
}
public void resetIterator() {
currentCol = currentRow = 0;
}
public boolean hasNext() {
// Not enough elements left
if (currentRow == listOfLists.size() - 1) {
return false;
}
// Definitely more elements left in the current list
if (listOfLists.get(currentRow).size() > currentCol + 1) {
return true;
}
return getNextNonEmptyList() == -1 ? false : true;
}
public T next() {
if (!hasNext()) {
return null;
}
// Definitely more elements left in the current list
if (listOfLists.get(currentRow).size() > currentCol) {
return listOfLists.get(currentRow).get(currentCol++);
}
currentRow = getNextNonEmptyList();
if (currentRow == -1) {
resetIterator();
return null;
} else {
currentCol = 0;
return listOfLists.get(currentRow).get(currentCol++);
}
}
private int getNextNonEmptyList() {
int tempRow = currentRow;
while (tempRow < listOfLists.size() - 1 && listOfLists.get(++tempRow).size() == 0);
if (tempRow == listOfLists.size() - 1) {
return -1;
} else {
return tempRow;
}
}
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList( 1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList( 6, 7, 8, 9);
List<Integer> list3 = Arrays.asList(10, 11, 12);
List<Integer> list4 = Arrays.asList(13, 14);
List<Integer> list5 = Arrays.asList(15);
List<Integer> list6 = Arrays.asList();
List<Integer> list7 = Arrays.asList();
List<Integer> list8 = Arrays.asList(16);
List<Integer> list9 = Arrays.asList();
List<List<Integer>> lists = Arrays.asList(list1, list2, list3, list4, list5, list6, list7, list8, list9);
ListOfLists<Integer> subject = new ListOfLists<>(lists);
while (subject.hasNext()) {
System.out.print(subject.next() + ", ");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment