1 33 package net.sf.jga.util; 34 35 import java.util.Iterator ; 36 import java.util.NoSuchElementException ; 37 import net.sf.jga.fn.UnaryFunctor; 38 39 47 48 public class FindIterator<T> implements Iterator <T>, Iterable <T> { 49 50 private T _next; 52 53 private Iterator <? extends T> _base; 55 56 private Boolean _baseHasNext; 58 59 62 public FindIterator(Iterator <? extends T> iter) { 63 _base = (iter != null) ? iter : new EmptyIterator<T>(); 64 } 65 66 72 public boolean findNext(UnaryFunctor<T,Boolean > filter) { 73 if (filter == null) 74 return hasNext(); 75 76 if (_baseHasNext != null) 78 { 79 if (_baseHasNext) 81 { 82 if (filter.fn(_next)) { 85 return true; 86 } 87 88 } 91 else { 92 return false; 93 } 94 } 95 96 while (_base.hasNext()) { 100 T elem = _base.next(); 101 if (filter.fn(elem)) { 102 _next = elem; 103 _baseHasNext = Boolean.TRUE; 104 return true; 105 } 106 } 107 108 _next = null; 109 _baseHasNext = Boolean.FALSE; 110 return false; 111 } 112 113 114 118 public Iterator <T> iterator() { return this; } 119 120 124 130 public boolean hasNext(){ 131 if (_baseHasNext != null) { 133 return _baseHasNext; 134 } 135 136 boolean b = _base.hasNext(); 140 _baseHasNext = Boolean.valueOf(b); 141 142 if (b) { 147 _next = _base.next(); 148 } 149 150 return b; 151 } 152 153 public T next() { 154 if (_baseHasNext == null) { 157 if (!hasNext()) { 158 throw new NoSuchElementException (); 159 } 160 } 161 162 else { 165 if (!_baseHasNext) { 166 throw new NoSuchElementException (); 167 } 168 } 169 170 T val = _next; 172 _next = null; 173 _baseHasNext = null; 174 return val; 175 } 176 177 public void remove() { throw new UnsupportedOperationException (); } 178 } 179 | Popular Tags |