This project has retired. For details please refer to its Attic page.
FilterIterator xref

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.chemistry.opencmis.jcr.util;
21  
22  import java.util.Iterator;
23  import java.util.NoSuchElementException;
24  
25  /**
26   * Iterator filtering out items which do not match a given predicate.
27   * @param <T>
28   */
29  public class FilterIterator<T> implements Iterator<T> {
30      private final Iterator<T> iterator;
31      private final Predicate<T> predicate;
32  
33      private T next;
34  
35      /**
36       * Create a new filtered iterator based on the given <code>iterator</code>.
37       *
38       * @param iterator  iterator to filter
39       * @param predicate  only item matching this predicate are included
40       */
41      public FilterIterator(Iterator<T> iterator, Predicate<T> predicate) {
42          this.iterator = iterator;
43          this.predicate = predicate;
44      }
45  
46      public boolean hasNext() {
47          while (next == null && iterator.hasNext()) {
48              T e = iterator.next();
49              if (predicate.evaluate(e)) {
50                  next = e;
51              }
52          }
53  
54          return next != null;
55      }
56  
57      public T next() {
58          if (hasNext()) {
59              T e = next;
60              next = null;
61              return e;
62          }
63          else {
64              throw new NoSuchElementException();
65          }
66      }
67  
68      public void remove() {
69          throw new UnsupportedOperationException();
70      }
71  
72  }