KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > polyglot > util > FilteringIterator


1 /*
2  * FilteringIterator.java
3  */

4
5 package polyglot.util;
6
7 import java.util.Iterator JavaDoc;
8 import java.util.Collection JavaDoc;
9
10 /**
11  * FilteringIterator
12  *
13  * Overview:
14  * This iterator wraps another iterator, and returns only those elements
15  * for which a given predicate is true.
16  *
17  * Does not support Remove.
18  **/

19 public final class FilteringIterator implements Iterator JavaDoc {
20   /**
21    * Constructs a new FilteringIterator which returns only those elements of
22    * <coll> which have <pred> true.
23    **/

24   public FilteringIterator(Collection JavaDoc coll, Predicate pred) {
25     this(coll.iterator(), pred);
26   }
27
28   /**
29    * Constructs a new FilteringIterator which returns all the elements
30    * of <iter>, in order, only when they have <pred> true.
31    **/

32   public FilteringIterator(Iterator JavaDoc iter, Predicate pred) {
33     backing_iterator = iter;
34     predicate = pred;
35     findNextItem();
36   }
37
38   public Object JavaDoc next() {
39     Object JavaDoc res = next_item;
40     if (res == null)
41       throw new java.util.NoSuchElementException JavaDoc();
42     findNextItem();
43     return res;
44   }
45
46   public boolean hasNext() {
47     return next_item != null;
48   }
49   
50   public void remove() {
51     throw new UnsupportedOperationException JavaDoc("FilteringIterator.remove");
52   }
53
54   // Advances the internal iterator.
55
private void findNextItem() {
56     while (backing_iterator.hasNext()) {
57       Object JavaDoc o = backing_iterator.next();
58       if (predicate.isTrue(o)) {
59     next_item = o;
60     return;
61       }
62     }
63     next_item = null;
64   }
65   
66   // AF: if next_item==null, this iterator has no more elts to yield.
67
// otherwise, this iterator will yield next_item, followed by
68
// those elements e of backing_iterator such that predicate.isTrue(e).
69
Object JavaDoc next_item;
70   Iterator JavaDoc backing_iterator;
71   Predicate predicate;
72 }
73
74
75
Popular Tags