gpt4 book ai didi

java - 迭代字符串列表以查看特定字符串是否存在于列表中的所有字符串中(Java/Groovy)

转载 作者:行者123 更新时间:2023-12-01 20:00:09 35 4
gpt4 key购买 nike

我有一个字符串列表(我从另一种方法获得),并且想要验证所有字符串中是否存在某个字符串。即,如果列表是 ["My name is Lindsey", "My name is Billy,"My name is John"] 并且我正在测试“name”是否存在于所有字符串中,则该方法应该返回 true。但是如果列表为 ["My name is Lindsey", "My name is Billy, "I'm John"],该方法应返回 false,因为“name”不在最后一个字符串中。 (我对编程真的很陌生,如果我没有使用正确的术语/符号,我很抱歉)。无论如何,这是我目前拥有的:

def verifyEachSuggestionContainsValueOf(String value) {
List<String> customerMessageSuggestions = customerMessageAutoSuggestions()
boolean stringPresent = false
for (String suggestion : customerMessageSuggestions) {
if (suggestion.contains(value)) {
stringPresent = true
}else{
return false
}
}
return stringPresent
}

这可行,但我觉得必须有一种更简洁的方法来做到这一点。任何建议将不胜感激。谢谢!

***已编辑以修复 For 循环内返回 stringPresent 的问题。

最佳答案

在纯 Java 中:

return list.stream().allMatch(s -> s.contains("name"));

在 Groovy 中:

return list.every { it.contains("name") }

关于java - 迭代字符串列表以查看特定字符串是否存在于列表中的所有字符串中(Java/Groovy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48271647/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com