gpt4 book ai didi

java - 如何检查一个 ArrayList of Strings 是否包含另一个 ArrayList of Strings 的子字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:48:21 26 4
gpt4 key购买 nike

List<String> actualList = Arrays.asList ("mother has chocolate", "father has dog");
List<String> expectedList = Arrays.asList ("mother", "father", "son", "daughter");

有没有办法检查 expectedList 是否包含 actualList 中字符串的任何子字符串?

我找到了一个嵌套的 for-each 解决方案:

public static boolean hasAny(List<String> actualList, List<String> expectedList) {
for (String expected: expectedList)
for (String actual: actualList)
if (actual.contains(expected))
return true;

return false;
}

我试图找到 lambda 解决方案,但我找不到。我发现的所有方法都检查 String#equals 而不是 String#contains

如果有这样的东西就好了:

CollectionsUtils.containsAny(actualList, exptectedList);

但它使用 String#equals 而不是 String#contains 来比较字符串。

编辑:

基于问题:如果 actualList 中的所有子字符串都是 expectedList 的一部分,我想得到 TRUE。下面凯文的解决方案对我有用。

最佳答案

这样的事情怎么样:

list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)))

Try it online.

  • allMatch 将检查所有内容是否为 true
  • anyMatch 将检查是否至少有一个为 true

这里有一些类似 Java 7 风格的东西,没有 lambda 和流,可以更好地理解正在发生的事情:

boolean allMatch = true;       // Start allMatch at true
for(String s1 : list1){
boolean anyMatch = false; // Start anyMatch at false inside the loop
for(String s2 : list2){
anyMatch = s1.contains(s2);// If any contains is true, anyMatch becomes true as well
if(anyMatch) // And stop the inner loop as soon as we've found a match
break;
}
allMatch = anyMatch; // If any anyMatch is false, allMatch becomes false as well
if(!allMatch) // And stop the outer loop as soon as we've found a mismatch
break;
}
return allMatch;

Try it online.


如果您更喜欢CollectionsUtils.containsAny(list1, list2),您可以在代码的其他地方重复使用,您总是可以自己制作一个:

public final class CollectionsUtil{
public static boolean containsAny(ArrayList<String> list1, ArrayList<String> list2){
return list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)));
// Or the contents of the Java 7 check-method above if you prefer it
}

private CollectionsUtil(){
// Util class, so it's not initializable
}
}

然后可以根据需要使用:

boolean result = CollectionsUtils.containsAny(actualList, expectedList);

Try it online.

关于java - 如何检查一个 ArrayList of Strings 是否包含另一个 ArrayList of Strings 的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537462/

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