12
List<String> listA = new ArrayList<String>();
listA.add("a");
listA.add("b");
listA.add("c");
listA.add("d");



List<String> listB = new ArrayList<String>();
listB.add("c");
listB.add("d");
listB.add("e");
listB.add("f");

ListB contains two elements that are also present in ListA ("c" and "d").

Is there a clean way to make sure that listB does not contain these or any other overlapping elements that may already exist in listA?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
jts
  • 1,629
  • 2
  • 13
  • 10

1 Answers1

20
listB.removeAll(listA)

This would make your listB contain only [e, f].

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    this only works out of the box with basic object type lists (string etc) for your own objects you need to define object.equals method so it will mean something with your object. read more on equals here:stackoverflow.com/questions/8338326/… – Gabriel H Dec 03 '14 at 11:00