检查一个 List<String> 是否包含另一个列表中的特定字符串

Check if one List<String> contains specific string from another list

我有一个 List<String> emails 包含电子邮件,另一个 List<String> keywords 包含关键字。对于 keywords 中的每个第 i 个值,第 i 个索引上应该有一个包含该值的字符串。

因此,如果 emails.get(0) == "quick brown fox",则 keywords.get(0) == "fox"

如果emails.get(5) == "foo bar",则keywords.get(5) == "foo"

我如何检查(for 循环除外)每封电子邮件是否包含关键字?

此代码使用 Java streams/maps 检查每封电子邮件是否包含各自的关键字。

boolean allEmailsContainKeyword(List<String> emails, List<String> keywords) {
    return !emails.stream().map(email -> email.contains(keywords.get(emails.indexOf(email)))).collect(Collectors.toList()).contains(false);
}

首先,可能需要检查两个列表的大小,然后比较相应的列表项,应该使用IntStream

public static boolean allKeywordsFound(List<String> emails, List<String> keywords) {
    return emails.size() == keywords.size() &&
        IntStream.range(0, emails.size())
            .allMatch(i -> emails.get(i).contains(keywords.get(i)));
}

我看到其他人正确回答了您的问题,但这是我对这个问题的看法。 我假设您希望按顺序检查电子邮件,所以这里有一段代码使用 Stream API 而不是 for 循环,我还将电子邮件列表和结果放在一起 Map 因为您没有指定是否要将生成的 boolean 值用于所有电子邮件,或者是否要为包含 same-position 关键字的每封电子邮件提供一个布尔值:

//mock data initialization
List<String> emails = new ArrayList<>();
List<String> keywords = new ArrayList<>();

//mock data initialization
emails.add("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
emails.add("eu lobortis elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis enim ut tellus elementum sagittis");
emails.add("Dignissim suspendisse in est ante in nibh mauris");

//mock data initialization
keywords.add("consectetur");
keywords.add("Foo");
keywords.add("Dignissim");

//initialized a list to contain whether a keyword exists for each email
List<Boolean> exists = new ArrayList<>();

//loaded it with boolean values (the exists List has the same order as the emails list)
emails.forEach(email -> exists.add(email
            .contains(keywords
                    .get(emails
                            .indexOf(email)))));

//since I don't know what you wanna do with the result, I decided to just put them together in a Map
//with the email string as the key and the existence variable as a value
LinkedHashMap mapOfTruth = new LinkedHashMap();
emails.forEach(email -> mapOfTruth.put(email, exists.get(emails.indexOf(email))));

输出

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua = true
eu lobortis elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis enim ut tellus elementum sagittis = false
Dignissim suspendisse in est ante in nibh mauris = true