检查电子邮件域是否在域列表中的最快方法

问题描述 投票:0回答:2

我想确保客户输入的电子邮件地址是企业帐户电子邮件,因为我们只与拥有自己域名的大公司合作。

我在此网站上列出了最常见的电子邮件域:https://email-verify.my-addr.com/list-of-most-popular-email-domains.php

我想要以最快的方式检查电子邮件是否没有在 Java 中获得这些域之一。

List<String> domains = ...
String email = "[email protected]";

Boolean domainsMatch = false;

//Some code to check the domains against the email

return !domainMatches;

我尝试了显而易见的方法

for (String domain: domains)
{
  if (email.contains(domain)) domainsMatch = true;
}

我想知道是否有更快更有效的方法

java arrays match
2个回答
0
投票

我能想到的一种有效方法(前提是您使用

Java 8
或更高版本)是使用
streams api
,它是专门设计用于更有效地对大型数据集进行操作的。

List<String> domains = ...
String email = "[email protected]";

boolean domainMatches = domains.stream()
    .anyMatch(email::contains);

return !domainMatches;

此外,正如@AndyTurner所指出的,你不应该使用

contains
,因为它可以匹配一些无效的地址(如
bob@gmailcom
)。因此,如果您正在寻找另一种方法,您可以使用 equals:

List<String> domains = ...
String email = "[email protected]";

String domain = email.split("@")[1];

boolean domainMatches = domains.stream()
    .anyMatch(domain::equals);

return !domainMatches;

编辑:(推荐方法)

根据评论和集思广益后,我想出了另一种比使用

streams
更有效的方法,那就是使用
HashSet
。比如:

List<String> domains = ...
String email = "[email protected]";

Set<String> domainSet = new HashSet<>(domains);
String domain = email.split("@")[1]; // You can also use indexOf and substring.

boolean domainMatches = domainSet.contains(domain);

return !domainMatches;

0
投票

“...我想要最快的方法来检查电子邮件是否没有 Java 中的这些域之一。...”

最快的解决方案是循环

List<String> domains = ...
String email = "[email protected]".toLowerCase(),
       s = email.substring(email.indexOf('@'));

Boolean domainsMatch = false;

//Some code to check the domains against the email

for (String domain: domains)
{
    if (domain.endsWith(s)) {
        domainsMatch = true;
        break;
    }
}

return domainsMatch;

或者,使用stream

List<String> domains = ...
String email = "[email protected]".toLowerCase(),
       s = email.substring(email.indexOf('@'));

//Some code to check the domains against the email

Boolean noMatch
    = domains.stream()
             .noneMatch(x -> x.toLowerCase().endsWith(s));
© www.soinside.com 2019 - 2024. All rights reserved.