Any Method which does the function opposite to that of retain all?

I have two lists like

List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<String>(Arrays.asList("A"));

List<String> result = list1.(SomeMethod)(list2) must return result = {"B","C"}

Is such method is available?


Solution 1:

There's list1.removeAll(list2)

/**
 * Removes from this list all of its elements that are contained in the
 * specified collection (optional operation).
 *
 * @param c collection containing elements to be removed from this list
 * @return <tt>true</tt> if this list changed as a result of the call
 * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
 *         is not supported by this list
 * @throws ClassCastException if the class of an element of this list
 *         is incompatible with the specified collection (optional)
 * @throws NullPointerException if this list contains a null element and the
 *         specified collection does not permit null elements (optional),
 *         or if the specified collection is null
 * @see #remove(Object)
 * @see #contains(Object)
 */
boolean removeAll(Collection<?> c);

Solution 2:

If you want to use the same logic as retainAll, and don't modify your 2 original lists, you can go for :

Collection retained = CollectionUtils.removeAll(list1,list2)

Or if you are sure that list2 contains only items from list1

Collection retained = CollectionUtils.disjunction(list1,list2)

Or

Collection retained = ListUtils.subtract(list1,list2)