-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPredicateIterator.java
More file actions
41 lines (35 loc) · 998 Bytes
/
Copy pathPredicateIterator.java
File metadata and controls
41 lines (35 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
/*
* http://chaoticjava.com/posts/how-to-write-iterators-really-really-fast/
*/
class PredicateIterator<T> implements Iterator<T> {
Iterator<? extends T> it;
private final Predicate pr;
private T nextElement;
boolean hasNextElement; // this boolean is required
public PredicateIterator(Iterator<T> iterator, Predicate predicate) {
this.it = iterator;
this.pr = predicate;
seekNext();
}
public T next() {
if (!hasNextElement) throw new NoSuchElementException();
T ret = nextElement;
seekNext();
return ret;
}
public boolean hasNext() {
return hasNextElement;
}
public void seekNext() {
hasNextElement = false;
nextElement = null;
while (it.hasNext() && !hasNextElement) {
T e = it.next();
if (pr.evaluate(e)) {
nextElement = e;
hasNextElement = true;
}
}
}
}