java - check if a substring is present in an arraylist of strings in java

╄→尐↘猪︶ㄣ 提交于 2019-12-24 14:29:43

问题


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


回答1:


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



回答2:


Using the Stream API you could check if the list has an element which contains "string2" and print to the console like this:

arr1.stream()
    .filter(e -> e.contains("string2"))
    .findFirst()
    .ifPresent(e -> System.out.println("Match found"));

However, you cannot avoid checking each element individually (until we find the first) because you're interested to see if a particular string contains a specific substring.




回答3:


Here is another way (make a string out of the arrayList):

String listString = String.join(", ", arr1);

      if (listString.contains("string2"))
      {
        System.out.println("Match found");
      }


来源:https://stackoverflow.com/questions/48132288/java-check-if-a-substring-is-present-in-an-arraylist-of-strings-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!