Removes all occurrences of the element in the given Collection - Java java.util

Java examples for java.util:Collection Element Remove

Description

Removes all occurrences of the element in the given Collection

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * 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  w ww.j a  va 2s . c om
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

public class Main{
    /**
     * Removes all occurrences of the element in the given {@link Collection}.
     * @param collection The {@link Collection} to remove from.
     * @param toRemove The element to remove.
     * @return {@code true} if at least one element was removed, {@code false} if the {@link Collection} was not modified.
     */
    public static <T> boolean removeComplete(Collection<T> collection,
            T toRemove) {
        if (collection != null) {
            Iterator<T> iter = collection.iterator();
            boolean changed = false;
            while (iter.hasNext()) {
                if (ObjectUtil.equals(iter.next(), toRemove)) {
                    iter.remove();
                    changed = true;
                }
            }
            return changed;
        } else {
            return false;
        }
    }
}

Related Tutorials