我有一個List<String>型別的電子郵件串列,還有另一個關鍵字List<String>。每封電子郵件都應該包含一個關鍵字 - 順序很重要 - 意思是,第一封電子郵件應該包含第一個關鍵字,依此類推。
如何檢查(for回圈除外)每個電子郵件片段是否包含關鍵字?
uj5u.com熱心網友回復:
首先,可能需要檢查兩個串列的大小,然后比較相應的串列項,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)));
}
uj5u.com熱心網友回復:
我看到其他人正確回答了您的問題,但這是我對這個問題的看法。我假設您希望按順序檢查電子郵件,所以這是一段使用Stream API而不是for回圈的代碼,我還將電子郵件串列和結果放在一起,Map因為您沒有指定是否希望結果boolean值為對于所有電子郵件,或者如果您想要包含相同位置關鍵字的每封電子郵件的布林值:
//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
uj5u.com熱心網友回復:
此代碼使用 Java 流/映射檢查每封電子郵件是否包含各自的關鍵字。
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426718.html
