Search code examples
javalistremoveallremove-if

Comparison of lists - remove elements


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 delete objects (e-mails) from the first list which is NOT on the second list (List2 - domains).

For example:
If List1 contains the email address "[email protected]" and the second List2 does NOT contain "@domain.com" - then I want to delete this email address (from list 1)

I know it may be duplicated post:
Remove objects from list - contains strings - Comparing the List
But I don't know how to create a negation (!) of these answers...

I will be grateful for your quick help


Solution

  • Based on the accepted answer in your other question, you'll just have to change the anyMatch to noneMatch:

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