1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springmodules.validation.util.collection;
18
19 import java.util.Iterator;
20 import java.util.NoSuchElementException;
21
22 import org.springmodules.validation.util.condition.Condition;
23
24
25
26
27
28
29 public class FilteredIterator extends ReadOnlyIterator {
30
31 private Condition condition;
32
33 private Iterator iterator;
34
35 private boolean initialized;
36
37 private boolean finished;
38
39 private Object nextElement;
40
41
42
43
44
45
46
47
48 public FilteredIterator(Iterator iterator, Condition condition) {
49 this.iterator = iterator;
50 this.condition = condition;
51 }
52
53 public boolean hasNext() {
54 initializeIfNeeded();
55 return !finished;
56 }
57
58 public Object next() {
59 if (!hasNext()) {
60 throw new NoSuchElementException();
61 }
62 Object result = nextElement;
63 advanceIterator();
64 return result;
65 }
66
67
68
69 protected void initializeIfNeeded() {
70 if (!initialized) {
71 advanceIterator();
72 initialized = true;
73 }
74 }
75
76 protected void advanceIterator() {
77 boolean assigned = false;
78 while (iterator.hasNext()) {
79 Object element = iterator.next();
80 if (condition.check(element)) {
81 nextElement = element;
82 assigned = true;
83 break;
84 }
85 }
86 finished = !assigned;
87 }
88
89 }