Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any method in the standard API to inverse retainAll()?

Is there any method which does the following for me in one shot :

List<String> list1 = new ArrayList<String>(Arrays.asList("A","B","C","D"));
List<String> list2 = new ArrayList<String>(Arrays.asList("B","C","E","F"));
List<String> list3 = new ArrayList<String>();
for(String element : list2){
   if(!list1.contains(element))
   list3.add(element);
}

As a result list3 should contain elements "E" & "F".

like image 687
pall Avatar asked Apr 27 '11 07:04

pall


2 Answers

Do you mean?

List<String> list3 = new ArrayList<String>(list2);
list3.removeAll(list1);

However, doing unions and intersections is usually best done using Sets rather than Lists. (And more efficiently)

Set<String> set3 = new LinkedHashSet<String>(set2);
set3.removeAll(set1);
like image 151
Peter Lawrey Avatar answered Sep 27 '22 19:09

Peter Lawrey


Or with Guava's Sets.intersection():

Lists.newArrayList(Sets.intersection(ImmutableSet.of(list1), ImmutableList.of(list2)));
like image 26
KARASZI István Avatar answered Sep 27 '22 20:09

KARASZI István