这样的事情怎么样:
list1.stream().allMatch(s1 -> list2.stream().anyMatch(s2 -> s1.contains(s2)))
> allMatch将检查一切是否正确
> anyMatch将检查是否至少有一个是真的
这里有类似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);