[英]Check if String Array contains a Substring without loop
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?
这种方法有什么问题?
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. 您正在检查
String
“ .csv”是否不包含Stream
任何元素,这与您想要的相反。
It should be: 它应该是:
if (!Arrays.stream(files).anyMatch(s -> s.contains(substring))) {
System.out.println("Not found:" + substring);
}
PS As commented, you can use noneMatch
instead of anyMatch
, which will save the need to negate the condition: PS如前所述,您可以使用
noneMatch
代替anyMatch
,这将节省否定条件的需要:
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
(ie treated as a suffix), you should use endsWith
instead of contains
. 如果仅在
String
末尾搜索“ .csv”子String
(即视为后缀),则应使用endsWith
而不是contains
。
You possibly need to check the file extension and can use endsWith
for it instead and improve your condition to: 您可能需要检查文件扩展名,并可以使用
endsWith
代替它,并将您的条件改善为:
if (Arrays.stream(files).noneMatch(a -> a.endsWith(substring))) {
System.out.println("Not found:" + substring);
}
I am not a streams guru, but I believe that you want something like this: 我不是流媒体专家,但我相信您想要这样的东西:
String[] files = new String[] { "Audit_20190204_061439.csv", "anotherFile" };
for (String file : files) {
if (file.endsWith(".csv")) {
System.out.println("found a CSV file");
}
}
I use String#endsWith
here because presumably .csv
refers to a file extension, and should only register a hit if occur at the end of the filename. 我在这里使用
String#endsWith
,因为.csv
大概是文件扩展名,并且仅在文件名末尾出现时才注册String#endsWith
。
We could also use String#matches
here: 我们也可以在这里使用
String#matches
:
Pattern pattern = Pattern.compile(".*\\.csv$");
for (String file : files) {
Matcher matcher = pattern.matcher(file);
if (matcher.find()) {
System.out.println("found a CSV file");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.