Search code examples
javaarraylistiteratorremoveall

Remove objects from list - contains strings - Comparing the List


My question is - How to remove objects from the list by comparing it with the second list.

List1 - The first list contains email addresses.
List2 - The second list contains only domains in the format "@domain.com" etc

I would like to remove objects (e-mails) from the first list that contain domains from the second list.

For example:
If List1 contain email address: "email@domain.com" and second List2 contain "@domain.com" - then I want to remove this email (from List1)

I tried to use:

List1.removeIf(s -> s.equals (List2));
List1.removeAll(List2);

Unfortunately, it does not filter my list as I would like.

I will be grateful for your quick help


Solution

  • Something like

    list1.removeIf(email -> list2.stream().anyMatch(email::endsWith));
    

    should work