问题描述
我想使用JAVA获取列表中包含".txt"
的字符串的第一个索引。没有做任何循环。因为我在File中有很多价值,例如:
["sample.txt","sample.csv","sample.docx","sample","sample.xlsx","sample2.txt,...];
我只需要“ sample.txt”
的索引List<String> files = Arrays.asList(fileList).stream()
.map(x -> x.getAbsolutePath())
.collect(Collectors.toList());
index = files.indexOf(?);
解决方法
您是否想使用:
List<String> list = Arrays.asList(fileList);
String first = list.stream(fileList)
.filter(x -> x.endsWith(".txt")) // or contains if the .txt can be in the middle
.findFirst()
.orElse(null); // you can even throw and exception using orElseThrow
// to get the index you can use
int index = list.indexOf(first);