blob: fdde82c9fe9b8bad10bbb6ebacc66edf16cab27d [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001/**
2 * Copyright 2012, Big Switch Networks, Inc.
3 * Originally created by David Erickson, Stanford University
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may
6 * not use this file except in compliance with the License. You may obtain
7 * a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations
15 * under the License.
16 **/
17
18package net.onrc.onos.of.ctl.util;
19
20import java.util.Iterator;
21import java.util.NoSuchElementException;
22
23/**
24 * An iterator that will filter values from an iterator and return only
25 * those values that match the predicate.
26 */
27public abstract class FilterIterator<T> implements Iterator<T> {
28 protected Iterator<T> subIterator;
29 protected T next;
30
31 /**
32 * Construct a filter iterator from the given sub iterator.
33 *
34 * @param subIterator the sub iterator over which we'll filter
35 */
36 public FilterIterator(Iterator<T> subIterator) {
37 super();
38 this.subIterator = subIterator;
39 }
40
41 /**
42 * Check whether the given value should be returned by the
43 * filter.
44 *
45 * @param value the value to check
46 * @return true if the value should be included
47 */
48 protected abstract boolean matches(T value);
49
50 // ***********
51 // Iterator<T>
52 // ***********
53
54 @Override
55 public boolean hasNext() {
56 if (next != null) {
57 return true;
58 }
59
60 while (subIterator.hasNext()) {
61 next = subIterator.next();
62 if (matches(next)) {
63 return true;
64 }
65 }
66 next = null;
67 return false;
68 }
69
70 @Override
71 public T next() {
72 if (hasNext()) {
73 T cur = next;
74 next = null;
75 return cur;
76 }
77 throw new NoSuchElementException();
78 }
79
80 @Override
81 public void remove() {
82 throw new UnsupportedOperationException();
83 }
84
85}