1

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

3 Answers 3

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

No it would not. filter(s->s.contains("string2") would.
0

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

2 Comments

This assumes that the search string does not contain commas :-)
Yes! forgot to mention that. Be careful about it, and if it is with commas, just replace it with an unused character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.