Java 检查字符串数组是否包含不带循环的子字符串
我希望在字符串数组中查找子字符串,而不使用循环。我正在使用:Java 检查字符串数组是否包含不带循环的子字符串,java,arrays,java-stream,Java,Arrays,Java Stream,我希望在字符串数组中查找子字符串,而不使用循环。我正在使用: 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";
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);
}
}
}
我总是找不到。该方法有什么问题?您正在检查
字符串“.csv”是否不包含流的任何元素,这与您想要的相反
应该是:
if (!Arrays.stream(files).anyMatch(s -> s.contains(substring))) {
System.out.println("Not found:" + substring);
}
注意:如前所述,您可以使用noneMatch
而不是anyMatch
,这将省去否定条件的需要:
if (Arrays.stream(files).noneMatch(s -> s.contains(substring))) {
System.out.println("Not found:" + substring);
}
如果只应在字符串
的末尾搜索“.csv”子字符串(即作为后缀处理),则应使用endsWith
,而不是contains
,我不是streams专家,但我相信您希望这样:
String[] files = new String[] { "Audit_20190204_061439.csv", "anotherFile" };
for (String file : files) {
if (file.endsWith(".csv")) {
System.out.println("found a CSV file");
}
}
我在这里使用String#endsWith
,因为大概.csv
指的是一个文件扩展名,只有在文件名末尾出现时才应该注册命中
我们也可以在这里使用String#匹配
:
Pattern pattern = Pattern.compile(".*\\.csv$");
for (String file : files) {
Matcher matcher = pattern.matcher(file);
if (matcher.find()) {
System.out.println("found a CSV file");
}
}
您可能需要检查文件扩展名,并可以改为使用endsWith
,并改善您的条件以:
if (Arrays.stream(files).noneMatch(a -> a.endsWith(substring))) {
System.out.println("Not found:" + substring);
}
+anyMatch()
->noneMatch()
OP可能想在这里使用String#endWith
,因为.csv
是一个扩展名,应该只出现在字符串的末尾。我建议不要在循环中使用file#matches()
,最好事先创建模式:模式.compile(“*.csv$”
@Lino,事实上你以前告诉过我这一点。我想旧习惯很难改掉:-(您只是通过流隐藏循环。这并不意味着该方法比简单易懂的for
循环更快。相反,请查看lambda的过度使用如何导致您犯下难以发现的错误(子字符串函数中的参数顺序错误)。