Returns a new Collection containing a - b. - Java java.util

Java examples for java.util:Collection Search

Description

Returns a new Collection containing a - b.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection a = java.util.Arrays.asList("asdf", "java2s.com");
        Collection b = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(subtract(a, b));
    }/*from w  ww . j a  va 2s .co m*/

    /**
     * Returns a new {@link Collection} containing <tt><i>a</i> - <i>b</i></tt>.
     * The cardinality of each element <i>e</i> in the returned
     * {@link Collection} will be the cardinality of <i>e</i> in <i>a</i> minus
     * the cardinality of <i>e</i> in <i>b</i>, or zero, whichever is greater.
     * 
     * @param a
     *            the collection to subtract from, must not be null
     * @param b
     *            the collection to subtract, must not be null
     * @return a new collection with the results
     * @see Collection#removeAll
     */
    public static <E> Collection<E> subtract(final Collection<E> a,
            final Collection<E> b) {
        if (a == null || b == null) {
            return null;
        }
        List<E> list = getArrayList(a);
        for (E e : list) {
            list.remove(e);
        }

        return list;
    }

    public static <E> ArrayList<E> getArrayList() {
        return new ArrayList<E>();
    }

    public static <E> ArrayList<E> getArrayList(int initialCapacity) {
        return new ArrayList<E>(initialCapacity);
    }

    public static <E> ArrayList<E> getArrayList(
            Collection<? extends E> collection) {
        return new ArrayList<E>(collection);
    }
}

Related Tutorials