user5155835 :
I want to find a substring in an array of strings, without using loop. I'm using:
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
String[] files = new String[]{"Audit_20190204_061439.csv","anotherFile"};
String substring= ".csv";
if(!Arrays.stream(files).anyMatch(substring::contains)) {
System.out.println("Not found:" + substring);
}
}
}
I'm always getting Not found. What is wrong with the approach?
Eran :
You are checking whether the String
".csv" does not contain any of the elements of your Stream
, which is the opposite of what you wanted.
It should be:
if (!Arrays.stream(files).anyMatch(s -> s.contains(substring))) {
System.out.println("Not found:" + substring);
}
P.S. As commented, you can use noneMatch
instead of anyMatch
, which will save the need to negate the condition:
if (Arrays.stream(files).noneMatch(s -> s.contains(substring))) {
System.out.println("Not found:" + substring);
}
and if the ".csv" substring should only be searched for in the end of the String
(i.e. treated as a suffix), you should use endsWith
instead of contains
.