misc/persolijn

osm-protobuf/src/main/java/osm/common/ConsumingIterator.java in master
Repositories | Summary | Log | Files

ConsumingIterator.java (1268B) download


 1package osm.common;
 2
 3import java.util.Iterator;
 4import java.util.function.Consumer;
 5import java.util.function.Predicate;
 6
 7public class ConsumingIterator<T> implements Iterator<T> {
 8    private final Iterator<T> original;
 9    private final Predicate<T> consumeWhere;
10    private final Consumer<T> consumer;
11
12    private T next = null;
13
14    public ConsumingIterator(Iterator<T> original, Predicate<T> consumeWhere, Consumer<T> consumer) {
15        this.original = original;
16        this.consumeWhere = consumeWhere;
17        this.consumer = consumer;
18    }
19
20    public ConsumingIterator(Iterator<T> original, Predicate<T> consumeWhere) {
21        this.original = original;
22        this.consumeWhere = consumeWhere;
23        this.consumer = null;
24    }
25
26    @Override
27    public boolean hasNext() {
28        if (next != null)
29            return true;
30
31        while (original.hasNext()) {
32            next = original.next();
33            if (!consumeWhere.test(next))
34                return true;
35
36            if (consumer != null)
37                consumer.accept(next);
38        }
39        return false;
40    }
41
42    @Override
43    public T next() {
44        if (!hasNext())
45            return null;
46
47        T willNext = next;
48        next = null;
49        return willNext;
50    }
51}