Add all elements in the target collection to the origin collection, and ignore elements which origin collection contained. - Java java.util

Java examples for java.util:Collection Contain

Description

Add all elements in the target collection to the origin collection, and ignore elements which origin collection contained.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection origin = java.util.Arrays.asList("asdf", "java2s.com");
        Collection target = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(addAllIgnoreContains(origin, target));
    }//from   w w  w  .j  a  v  a2 s .c om

    /**
     * Add all elements in the target collection to the origin collection, and
     * ignore elements which origin collection contained.
     */
    public static <T> Collection<T> addAllIgnoreContains(
            Collection<T> origin, Collection<T> target) {
        if (origin == null) {
            return null;
        }

        List<T> temp = new ArrayList<T>();
        if (!isEmpty(target)) {
            Iterator<T> it = target.iterator();
            while (it.hasNext()) {
                T object = it.next();
                if (!origin.contains(object)) {
                    temp.add(object);
                }
            }
        }

        addAll(origin, temp);
        return origin;
    }

    /**
     * Check if the specified collection is empty(null or size is zero)?
     */
    public static boolean isEmpty(Collection<?> collection) {
        if (size(collection) == 0) {
            return true;
        }
        return false;
    }

    /**
     * Wrap {@link Collection#addAll(Collection)} method for avoid
     * {@link NullPointerException}.
     */
    public static <T> boolean addAll(Collection<T> origin,
            Collection<T> target) {
        if (origin == null || target == null) {
            return false;
        }
        return origin.addAll(target);
    }

    /**
     * Get the size of specified collection.
     */
    public static int size(Collection<?> collection) {
        if (collection == null) {
            return 0;
        }
        return collection.size();
    }
}

Related Tutorials