Umesh Krishnaswamy | 345ee99 | 2012-12-13 20:29:48 -0800 | [diff] [blame] | 1 | /** |
| 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 | |
| 18 | package net.floodlightcontroller.util; |
| 19 | |
| 20 | import java.util.Iterator; |
| 21 | import 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 | */ |
| 27 | public 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 | * @param subIterator the sub iterator over which we'll filter |
| 34 | */ |
| 35 | public FilterIterator(Iterator<T> subIterator) { |
| 36 | super(); |
| 37 | this.subIterator = subIterator; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Check whether the given value should be returned by the |
| 42 | * filter |
| 43 | * @param value the value to check |
| 44 | * @return true if the value should be included |
| 45 | */ |
| 46 | protected abstract boolean matches(T value); |
| 47 | |
| 48 | // *********** |
| 49 | // Iterator<T> |
| 50 | // *********** |
| 51 | |
| 52 | @Override |
| 53 | public boolean hasNext() { |
| 54 | if (next != null) return true; |
| 55 | |
| 56 | while (subIterator.hasNext()) { |
| 57 | next = subIterator.next(); |
| 58 | if (matches(next)) |
| 59 | return true; |
| 60 | } |
| 61 | next = null; |
| 62 | return false; |
| 63 | } |
| 64 | |
| 65 | @Override |
| 66 | public T next() { |
| 67 | if (hasNext()) { |
| 68 | T cur = next; |
| 69 | next = null; |
| 70 | return cur; |
| 71 | } |
| 72 | throw new NoSuchElementException(); |
| 73 | } |
| 74 | |
| 75 | @Override |
| 76 | public void remove() { |
| 77 | throw new UnsupportedOperationException(); |
| 78 | } |
| 79 | |
| 80 | } |