Java Collection First removeFirst(Collection collection, int numToRemove)

Here you can find the source of removeFirst(Collection collection, int numToRemove)

Description

Removes and returns the first n items from the given collection.

License

Open Source License

Parameter

Parameter Description
collection a parameter
numToRemove a parameter

Return

List

Declaration

public static List removeFirst(Collection collection, int numToRemove) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2000, 2006 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  www  . j ava 2  s.  co  m
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;
import java.util.Collection;

import java.util.Iterator;
import java.util.List;

public class Main {
    /**
     * Removes and returns the first n items from the given collection.
     * 
     * @param collection
     * @param numToRemove
     * @return List
     */
    public static List removeFirst(Collection collection, int numToRemove) {
        int toRemove = Math.min(collection.size(), numToRemove);

        List removed = new ArrayList(toRemove);

        Iterator iter = collection.iterator();

        for (int idx = 0; idx < toRemove; idx++) {
            removed.add(iter.next());

            iter.remove();
        }

        return removed;
    }
}

Related

  1. getFirstOrNull(final Collection collection)
  2. getFirstSortedItem( Collection items, T defaultValue)
  3. getUnionSize(Collection firstCollection, Collection secondCollection)
  4. intersect(Collection firstSet, Collection secondSet)
  5. nullSafeFirstElement(Collection collection)
  6. removeFirst(Collection c)
  7. sub(Collection coll, int first, int size)
  8. subtract(Collection firstCollection, Collection secondCollection)
  9. union(Collection firstSet, Collection secondSet)