###问题描述
实现一个跳过null值的迭代器
[null,"1","2","3",null,"4",null]->["1","2","3","4"]
[null]->[]
[]->[]
###原来
Iterator iterator = new Iterator() {
private Iterator sourceIterator = source.iterator();
private String next;
public boolean hasNext() {
while (sourceIterator.hasNext()) {
next = sourceIterator.next();
if (next != null) {
return true;
}
}
next = null;
return false;
}
public String next() {
while (next == null) {
next = sourceIterator.next();
}
String temp = next;
next = null;
return temp;
}
public void remove() {
}
};
我需要写的如此复杂,才能保持Iterator特性,针对第一个case连续调用5次next方法抛出异常
###使用Guava
Iterator iterator = new AbstractIterator() {
private Iterator sourceIterator = source.iterator();
@Override protected String computeNext() {
while (sourceIterator.hasNext()) {
String next = sourceIterator.next();
if (next != null) {
return next;
}
}
return endOfData();
}
};
只需要关注如何获取下一个值就可以了,不需要关注如何实现hasNext方法。
需要注意:AbstractIterator不支持remove方法