Java Iterator max(final Iterator iter, final int max)

Here you can find the source of max(final Iterator iter, final int max)

Description

don't return more elements than given by max

License

Apache License

Parameter

Parameter Description
T a parameter
iter a parameter
max a parameter

Declaration

public static <T> Iterator<T> max(final Iterator<T> iter, final int max) 

Method Source Code

//package com.java2s;
/**/*w w w .  ja v a 2  s  .c o m*/
 * Copyright 2010 Molindo GmbH
 *
 * 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.Iterator;

import java.util.NoSuchElementException;

public class Main {
    /**
     * don't return more elements than given by max
     * 
     * @param <T>
     * @param iter
     * @param max
     * @return
     */
    public static <T> Iterator<T> max(final Iterator<T> iter, final int max) {
        return new Iterator<T>() {

            int _remaining = max;

            @Override
            public boolean hasNext() {
                return _remaining > 0 && iter.hasNext();
            }

            @Override
            public T next() {
                if (_remaining <= 0) {
                    throw new NoSuchElementException();
                }
                _remaining--;
                return iter.next();
            }

            @Override
            public void remove() {
                iter.remove();
            }

        };
    }

    /**
     * 
     * @param <T>
     * @param iter
     * @return the next element if available, <code>null</code> otherwise
     */
    public static <T> T next(final Iterator<T> iter) {
        return iter == null || !iter.hasNext() ? null : iter.next();
    }
}

Related

  1. iterable(Iterator iterator)
  2. length(Iterator iter)
  3. limit(final Iterator iterator, final int limit)
  4. listOfIterator(Iterator iterator)
  5. makeCollection(final Iterator i)
  6. mergeIterator( final Iterator iterator1, final Iterator iterator2)
  7. moveNext(Iterator iterator)
  8. multiIterator(Iterator... iterable)
  9. multiply(String string, Iterator placeholders, Iterator replacements)