Here you can find the source of filtered(final Iterator
Parameter | Description |
---|---|
iterator | a parameter |
filter | a parameter |
public static <E> Iterator<E> filtered(final Iterator<E> iterator, final BitSet filter)
//package com.java2s; /******************************************************************************* * Copyright 2012 Danny Kunz//www. j ava 2 s. c o m * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ import java.util.BitSet; import java.util.Iterator; import java.util.NoSuchElementException; public class Main { /** * Returns an {@link Iterator} which returns a filtered subset of the given {@link Iterator} based on the given filter * {@link BitSet} * * @param iterator * @param filter * @return new {@link Iterator} instance */ public static <E> Iterator<E> filtered(final Iterator<E> iterator, final BitSet filter) { if (iterator == null) { return empty(); } return new Iterator<E>() { private int index = 0; private boolean hasNoMoreFilteredElements = false; @Override public boolean hasNext() { forwardToNextFilterBit(iterator, filter); return !this.hasNoMoreFilteredElements && iterator.hasNext(); } private void forwardToNextFilterBit(final Iterator<E> iterator, final BitSet filter) { if (!this.hasNoMoreFilteredElements) { int nextSetBit = -1; while (this.index >= 0 && this.index < (nextSetBit = filter.nextSetBit(this.index)) && iterator.hasNext()) { this.fetchElement(); } this.hasNoMoreFilteredElements = nextSetBit < 0; } } @Override public E next() { if (this.hasNext()) { return fetchElement(); } throw new NoSuchElementException(); } private E fetchElement() { this.index++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Returns an empty {@link Iterator} * * @return */ public static <E> Iterator<E> empty() { return new Iterator<E>() { @Override public boolean hasNext() { return false; } @Override public E next() { throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }