Java List Subtract subtract(final List list1, final List list2)

Here you can find the source of subtract(final List list1, final List list2)

Description

Subtracts all elements in the second list from the first list, placing the results in a new list.

License

Open Source License

Parameter

Parameter Description
list1 the list to subtract from
list2 the list to subtract

Exception

Parameter Description
NullPointerException if either list is null

Return

a new list containing the results

Declaration

public static List subtract(final List list1, final List list2) 

Method Source Code


//package com.java2s;
/*/*w  ww  . j a  va 2  s  . c om*/
 * Copyright (c) 2007-2016 AREasy Runtime
 *
 * This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed Software");
 * you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either version 2.1 of the License,
 * or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 */

import java.util.*;

public class Main {
    /**
     * Subtracts all elements in the second list from the first list,
     * placing the results in a new list.
     * <p/>
     * This differs from {@link List#removeAll(Collection)} in that
     * cardinality is respected; if <Code>list1</Code> contains two
     * occurrences of <Code>null</Code> and <Code>list2</Code> only
     * contains one occurrence, then the returned list will still contain
     * one occurrence.
     *
     * @param list1 the list to subtract from
     * @param list2 the list to subtract
     * @return a new list containing the results
     * @throws NullPointerException if either list is null
     */
    public static List subtract(final List list1, final List list2) {
        final ArrayList result = new ArrayList(list1);
        final Iterator iterator = list2.iterator();

        while (iterator.hasNext()) {
            result.remove(iterator.next());
        }

        return result;
    }
}

Related

  1. subtract(final List list1, final List list2)
  2. subtract(final List result, final Object o1, final Object o2)
  3. subtract(final String[] input, final String[] list)
  4. subtract(List a, List b)
  5. subtract(List vector, int[] sparseVector)