java-检查子字符串是否存在于Java中的字符串数组列表中 [英] java - check if a substring is present in an arraylist of strings in java
问题描述
假设我有一个具有以下值的arraylist(arr1):
存在string1"存在string2"存在string3"存在string4"
我想查看子字符串'string2'是否存在于此arraylist中.通过遍历arraylist并使用"get"按索引,我在每个索引处提取了元素,然后对"Strings"使用"contains"方法,我在搜索"string2"并找到了匹配项
for(int i = 0; i< arr1.size(); i ++){字符串s1 = arr1.get(i);如果(s1.contains("string2")){System.out.println(找到匹配项");}}
是否可以使用arraylist本身的"contains"方法并执行相同的操作,而不是循环遍历arraylist并为"String"使用"contains"方法来实现此目的.有人可以让我知道吗.
谢谢
您不能使用 ArrayList
的 contains
方法,因为您无法绕过每个字符串./p>
在Java 8中,您可以使用流来隐藏循环:
boolean found = arr1.stream().anyMatch(s-> s.contains("string2"));
suppose i've an arraylist (arr1) with the following values:
"string1 is present"
"string2 is present"
"string3 is present"
"string4 is present"
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");
}
}
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.
Thanks
You cannot use contains
method of ArrayList
, because you cannot get around checking each string individually.
In Java 8 you can hide the loop by using streams:
boolean found = arr1.stream().anyMatch(s -> s.contains("string2"));
这篇关于java-检查子字符串是否存在于Java中的字符串数组列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!