Guava學習筆記-自定義迭代器

###問題描述
實現一個跳過null值的迭代器
[null,"1","2","3",null,"4",null]->["1","2","3","4"]
[null]->[]
[]->[]
###原來ide

Iterator<String> iterator = new Iterator<String>() {
    private Iterator<String> 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方法拋出異常
###使用Guavacode

Iterator<String> iterator = new AbstractIterator<String>() {
    private Iterator<String> sourceIterator = source.iterator();
    @Override protected String computeNext() {
        while (sourceIterator.hasNext()) {
            String next = sourceIterator.next();
            if (next != null) {
                return next;
            }
        }
        return endOfData();
    }
};

只須要關注如何獲取下一個值就能夠了,不須要關注如何實現hasNext方法。
須要注意:AbstractIterator不支持remove方法rem

相關文章
相關標籤/搜索