Reputation: 95
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
Upvotes: 1
Views: 3022
Reputation: 56489
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.
Upvotes: 1
Reputation: 196
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");
}
Upvotes: 0
Reputation: 727067
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"));
Upvotes: 2