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".
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);
Or with Guava's Sets.intersection()
:
Lists.newArrayList(Sets.intersection(ImmutableSet.of(list1), ImmutableList.of(list2)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With