java - 检查 java 中的字符串数组列表中是否存在子字符串 [英] java - check if a substring is present in an arraylist of strings in java

查看:32
本文介绍了java - 检查 java 中的字符串数组列表中是否存在子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有以下值的数组列表 (arr1):

suppose i've an arraylist (arr1) with the following values:

"string1 is present"
"string2 is present"
"string3 is present"
"string4 is present"

我想看看这个数组列表中是否存在子字符串string2".通过循环遍历数组列表并按索引使用get",我在每个索引处提取元素,然后对字符串"使用包含"方法,我搜索了string2"并找到了匹配项

i wanted to see if the substring 'string2' is present in this arraylist. by looping through the arraylist and using 'get' by index i extracted element at each index and then using 'contains' method for 'Strings' i'm searched for 'string2' and found a match

for (int i=0;i<arr1.size(); i++)
{
  String s1=arr1.get(i);
  if (s1.contains("string2"))
  {
    System.out.println("Match found");
  }
}

有没有办法使用arraylist本身的'contains'方法并做同样的事情,而不是我循环遍历arraylist并使用'String'的'contains'方法来实现这一点.有人可以告诉我吗.

is there a way to use the 'contains' method of the arraylist itself and do the same instead of me looping through the arraylist and using the 'contains' method for 'String' to achieve this. Can someone please let me know.

谢谢

推荐答案

您不能使用 ArrayListcontains 方法,因为您无法绕过单独检查每个字符串.

You cannot use contains method of ArrayList, because you cannot get around checking each string individually.

在 Java 8 中,您可以使用流来隐藏循环:

In Java 8 you can hide the loop by using streams:

boolean found = arr1.stream().anyMatch(s -> s.contains("string2"));

这篇关于java - 检查 java 中的字符串数组列表中是否存在子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆