在 JAVA 中不使用循环获取列表中包含“.txt”的索引

Get index that contains ".txt" in the list without using loop in JAVA

我想使用 JAVA 获取列表中包含 ".txt" 的字符串的第一个索引。没有做任何循环。因为我在文件中有很多价值,例如:

["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);