英文:
Get index that contains ".txt" in the list without using loop in JAVA
问题
我想要在包含 ".txt"
的字符串列表<String> 中获取第一个索引,使用JAVA。不使用任何循环。因为我在文件中有很多值,例如:
["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(?);
英文:
I would like to get the first index of a string that contains a ".txt"
in the list<String> using JAVA. without doing any loop. Because I have lots of value in File like :
["sample.txt", "sample.csv","sample.docx","sample","sample.xlsx","sample2.txt, ...];
I only need the index of "sample.txt"
List<String> files = Arrays.asList(fileList).stream()
.map(x -> x.getAbsolutePath())
.collect(Collectors.toList());
index = files.indexOf(?);
答案1
得分: 2
你是否希望使用:
List<String> list = Arrays.asList(fileList);
String first = list.stream(fileList)
.filter(x -> x.endsWith(".txt")) // 如果 .txt 可能出现在中间,可以使用 contains
.findFirst()
.orElse(null); // 甚至可以使用 orElseThrow 抛出异常
// 要获取索引,可以使用
int index = list.indexOf(first);
英文:
Are you looking to use :
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论