001 /*
002 * This file is part of the Jikes RVM project (http://jikesrvm.org).
003 *
004 * This file is licensed to You under the Eclipse Public License (EPL);
005 * You may not use this file except in compliance with the License. You
006 * may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/eclipse-1.0.php
009 *
010 * See the COPYRIGHT.txt file distributed with this work for information
011 * regarding copyright ownership.
012 */
013 package org.jikesrvm.compilers.opt.util;
014
015 /**
016 * A <code>FilterIterator</code> filters and maps a source
017 * <code>Iterator</code> to generate a new one.
018 */
019 public class FilterIterator<T> implements java.util.Iterator<T> {
020 final java.util.Iterator<T> i;
021 final Filter<T> f;
022 private T next = null;
023 private boolean done = false;
024
025 public FilterIterator(java.util.Iterator<T> i, Filter<T> f) {
026 this.i = i;
027 this.f = f;
028 advance();
029 }
030
031 private void advance() {
032 while (i.hasNext()) {
033 next = i.next();
034 if (f.isElement(next)) {
035 return;
036 }
037 }
038 done = true;
039 }
040
041 public T next() {
042 if (done) {
043 throw new java.util.NoSuchElementException();
044 }
045 T o = next;
046 advance();
047 return f.map(o);
048 }
049
050 public boolean hasNext() {
051 return !done;
052 }
053
054 public void remove() {
055 throw new java.lang.UnsupportedOperationException();
056 }
057
058 public static class Filter<T> { // override with your mapping.
059
060 public boolean isElement(Object o) {
061 return true;
062 }
063
064 public T map(T o) {
065 return o;
066 }
067 }
068 }