Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
MRavindran Avatar asked Aug 18 '15 06:08

MRavindran


2 Answers

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);
like image 50
Eran Avatar answered Oct 08 '22 20:10

Eran


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)
like image 1
Olivier Royo Avatar answered Oct 08 '22 18:10

Olivier Royo