Is there any method in the standard API for calling the keepAll () method?

Is there any method that 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 the elements "E" and "F".

+5
source share
2 answers

Do you mean?

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

However, making unions and intersections is usually best done using sets, not lists. (And more efficiently)

Set<String> set3 = new LinkedHashSet<String>(set2);
set3.removeAll(set1);
+11
source

Or with Guava Sets.intersection():

Lists.newArrayList(Sets.intersection(ImmutableSet.of(list1), ImmutableList.of(list2)));
+1
source

All Articles