Remove objects from list - contains strings - Comparing the List

蓝咒 提交于 2019-12-10 17:41:30

问题


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


回答1:


Something like

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

should work




回答2:


First, create a HashSet with your domains:

Set<String> domains = new HashSet<>(list2);

Now, use removeIf in the first list:

list1.removeIf(email -> domains.contains("@" + email.split("@")[1]));

The idea to use a Set (instead of the original list2) is to optimize the search, i.e. to make contains run in O(1) amortized time.

Note: I'm assuming all domains in list2 start with "@".




回答3:


You can create a new list of objects to be removed from first list and after delete them:

List<String> objectsToBeRemoved = list1.stream()
                                        .filer(email-> isNotValidEmail(email,list2))
                                        .collect(toList());
list1.removeAll(objectsToBeRemoved);

Another option is to use removeIf:

    List<String> emails = new ArrayList<>(Arrays.asList("email@domain.com", "email2@domain.com","ssss@ff.com"));
    List<String> domains = new ArrayList<>(Arrays.asList("@domain.com"));
    emails.removeIf(email -> isNotValidEmail(domains, email));

private boolean isNotValidEmail(List<String> domains, String email) {
    return domains.stream()
            .anyMatch(email::endsWith);
}


来源:https://stackoverflow.com/questions/52817109/remove-objects-from-list-contains-strings-comparing-the-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!