View Javadoc

1   /*
2    * Copyright 2004-2009 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * An wrapper iterator that filters out items from the underlying iterator based on a condition.
26   *
27   * @author Uri Boness
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       * Constructs a new FilteredIterator with given iterator to wrap and a condition. The constructed iterator will
43       * return only the element that adhere to the given condition.
44       *
45       * @param iterator The iterator to wrap.
46       * @param condition The condition that determines what elements should be returned by this iterator.
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      //=============================================== Helper Methods ===================================================
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  }