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

问题描述

我想使用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);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...