-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathFilteredIterator.java
More file actions
38 lines (30 loc) · 989 Bytes
/
FilteredIterator.java
File metadata and controls
38 lines (30 loc) · 989 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
package org.psjava.util;
import java.util.Iterator;
import java.util.function.Predicate;
public class FilteredIterator {
public static <T> Iterator<T> create(final Iterator<? extends T> a, final Predicate<T> filter) {
return new ReadOnlyIterator<T>() {
T next = null;
Iterator<? extends T> cursor = a;
@Override
public boolean hasNext() {
tryToStepNext();
return next != null;
}
@Override
public T next() {
tryToStepNext();
T r = next;
next = null;
return r;
}
private void tryToStepNext() {
while (next == null && cursor.hasNext()) {
T value = cursor.next();
if (filter.test(value))
next = value;
}
}
};
}
}