3 回答
TA贡献1802条经验 获得超5个赞
这样的事情怎么样:
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<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);
在线试一下。
TA贡献1998条经验 获得超6个赞
我 99% 确定您不是在hasAny这里寻找最受好评的答案,而是您想查看所有 fromexpectedList是否包含在actualList. 为此,首先创建 aSet和它的工作将是有益的(因为contains是O(1)forHashSet和反对O(n)for List)。
现在想一想,因为您只需要contains,您可以将其拆分actualList并从中创建独特的单词:
private static boolean test(List<String> actualList, List<String> expectedList) {
Pattern p = Pattern.compile("\\s+");
Set<String> set = actualList.stream()
.flatMap(p::splitAsStream)
.collect(Collectors.toSet());
return expectedList.stream().allMatch(set::contains);
}
TA贡献1802条经验 获得超10个赞
public static boolean containsAny(List<String> actualList, List<String> expectedList) {
final Pattern words = Pattern.compile("\\s+");
return actualList.stream()
.flatMap(words::splitAsStream)
.distinct()
// .allMatch(expectedList::contains)
.anyMatch(expectedList::contains);
}
添加回答
举报