java怎么检测一个字符串中是否有包含另外一个字符串,如何检查字符串的ArrayList是否包含另一个字......

这样的事情怎么样:

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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值