Java Utililty Methods Collection Remove

List of utility methods to do Collection Remove

Description

The list of methods to do Collection Remove are organized into topic(s).

Method

voidremoveArrayToCollection(T[] array, Collection collection)
Removes
for (int i = 0; i < array.length; i++) {
    if (array[i] != null) {
        collection.remove(array[i]);
Listremoved(Collection old, Collection nu)
removed
List<String> removed = null;
for (String s : old) {
    if (!nu.contains(s)) {
        if (removed == null) {
            removed = new ArrayList<String>(old.size());
        removed.add(s);
return removed;
Collectionremoved(Collection a, Collection b)
returns the elements added in List a with respect to b
Collection<T> aCopy = new ArrayList<T>(a);
Collection<T> bCopy = new ArrayList<T>(b);
Collection<T> added = added(a, b);
aCopy.removeAll(added);
bCopy.removeAll(aCopy);
return bCopy;
voidremoveDuplicates(Collection collection)
* Removes duplicates from collection based on its natural comparator or equality operator.
try {
    HashSet hs = new HashSet();
    Object obj = null;
    for (Iterator it = collection.iterator(); it.hasNext();) {
        obj = (Object) it.next();
        if (hs.contains(obj))
            it.remove();
        else
...
CollectionremoveDuplicates(Collection original)
Brute force, for when HashSet and TreeSet won't work (e.g.
ArrayList result = new ArrayList();
for (Iterator i = original.iterator(); i.hasNext();) {
    Object item = i.next();
    if (!result.contains(item)) {
        result.add(item);
return result;
...
booleanremoveDuplicates(Collection p_collection)
Removes duplicate objects from the Collection.
if (p_collection == null) {
    return false;
HashSet set = new HashSet(p_collection.size());
Iterator it = p_collection.iterator();
while (it.hasNext()) {
    set.add(it.next());
if (set.size() != p_collection.size()) {
    p_collection.clear();
    p_collection.addAll(set);
    return true;
return false;
CollectionremoveDuplicates(Collection objects)
remove Duplicates
LinkedHashSet<K> newCollection = new LinkedHashSet<K>();
K object = null;
newCollection.addAll(objects); 
return newCollection;
ListremoveDuplicates(Collection elements)
This does not change the passed in elements collection, it returns a new list Compared to just using Set, this preserves the order of the passed in collection
Set<T> added = new HashSet<>();
List<T> res = new ArrayList<>();
for (T e : elements) {
    if (!added.contains(e)) {
        res.add(e);
        added.add(e);
return res;
ObjectremoveElement(Collection coll)
Removes and returns an arbitrary element from the collection
Object ele = getAnElement(coll);
coll.remove(ele);
return ele;
TremoveElement(final int index, final Collection coll)
makes sense only if iteration order deterministic!
return getElement(true, index, coll);