作者:Xlady贩卖__铺 | 来源:互联网 | 2022-12-03 17:22
这样的事情怎么样:
list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)))
在线尝试.
allMatch
将检查是否一切 true
anyMatch
将检查是否至少有一个 true
这里有类似Java 7风格的东西,没有lambdas和流,可以更好地理解发生的事情:
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;
在线尝试.
如果您希望拥有一个CollectionsUtils.containsAny(list1, list2)
可以在代码中重复使用的代码,那么您可以自己创建一个:
public final class CollectionsUtil{
public static boolean containsAny(ArrayList list1, ArrayList 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);
在线尝试.
1> Kevin Cruijs..:
这样的事情怎么样:
list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)))
在线尝试.
allMatch
将检查是否一切 true
anyMatch
将检查是否至少有一个 true
这里有类似Java 7风格的东西,没有lambdas和流,可以更好地理解发生的事情:
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;
在线尝试.
如果您希望拥有一个CollectionsUtils.containsAny(list1, list2)
可以在代码中重复使用的代码,那么您可以自己创建一个:
public final class CollectionsUtil{
public static boolean containsAny(ArrayList list1, ArrayList 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);
在线尝试.
@Eugene看起来你确实是对的.我刚刚赞成你的回答.与'O(n)`List复杂度相比,`O(1)`设置复杂度的好方法.正如我在上面的评论中与_Johny Henly_讨论的那样,我不确定OP的意图是什么/不再是......他到目前为止也没有回复评论,他的原始代码已经被其他人修改过了(虽然原始代码段的行为与当前的新代码段有些相似.根据他的原始代码,我确实怀疑你的答案值得在这里勾选.