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 */ 013package 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 */ 019public 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 @Override 042 public T next() { 043 if (done) { 044 throw new java.util.NoSuchElementException(); 045 } 046 T o = next; 047 advance(); 048 return f.map(o); 049 } 050 051 @Override 052 public boolean hasNext() { 053 return !done; 054 } 055 056 @Override 057 public void remove() { 058 throw new java.lang.UnsupportedOperationException(); 059 } 060 061 public static class Filter<T> { // override with your mapping. 062 063 public boolean isElement(Object o) { 064 return true; 065 } 066 067 public T map(T o) { 068 return o; 069 } 070 } 071}