blob: fac4e7a72a96deb2f083d04c7e00292b8fabce01 [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
Ray Milkey269ffb92014-04-03 14:43:30 -07002 * 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 **/
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080017
18package net.floodlightcontroller.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
Ray Milkey269ffb92014-04-03 14:43:30 -070033 *
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080034 * @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
Ray Milkey269ffb92014-04-03 14:43:30 -070044 *
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080045 * @param value the value to check
46 * @return true if the value should be included
47 */
48 protected abstract boolean matches(T value);
Ray Milkey269ffb92014-04-03 14:43:30 -070049
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080050 // ***********
51 // Iterator<T>
52 // ***********
53
54 @Override
55 public boolean hasNext() {
56 if (next != null) return true;
Ray Milkey269ffb92014-04-03 14:43:30 -070057
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080058 while (subIterator.hasNext()) {
59 next = subIterator.next();
60 if (matches(next))
61 return true;
62 }
63 next = null;
64 return false;
65 }
66
67 @Override
68 public T next() {
69 if (hasNext()) {
70 T cur = next;
71 next = null;
72 return cur;
73 }
74 throw new NoSuchElementException();
75 }
76
77 @Override
78 public void remove() {
79 throw new UnsupportedOperationException();
80 }
81
82}