-2

i wanted to compare two ArrayList arrays and delete the different elements.

List<String> al1 = new ArrayList<String>();
List<String> al2 = new ArrayList<String>();

al1.add("222");

al2.add("222");
al2.add("333");

System.out.println(al1);
System.out.println(al2);

The output of println is:

[222]
[222, 333]

I want to remove the 333 in the second array because it is not in the first one how can i achieve this ?

Thanks in advance.

Computer85
  • 13
  • 2
  • 5

1 Answers1

0

You can do this with java.util.List.retainAll(Collection<?>):

public static void main(String[] args) {
   List<String> al1 = new ArrayList<String>();
   List<String> al2 = new ArrayList<String>();

   al1.add("222");

   al2.add("222");
   al2.add("333");

   al1.retainAll(al2);
   al2.retainAll(al1); // See Stultuske's comment.
   System.out.println(al1);
   System.out.println(al2);
}
Marteng
  • 1,179
  • 13
  • 31