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

huangapple go评论60阅读模式
英文:

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

问题

我想要在包含 &quot;.txt&quot; 的字符串列表<String> 中获取第一个索引,使用JAVA。不使用任何循环。因为我在文件中有很多值,例如:

[&quot;sample.txt&quot;, &quot;sample.csv&quot;,&quot;sample.docx&quot;,&quot;sample&quot;,&quot;sample.xlsx&quot;,&quot;sample2.txt, ...];

我只需要 "sample.txt" 的索引:

List&lt;String&gt; files = Arrays.asList(fileList).stream()
                             .map(x -&gt; x.getAbsolutePath())
                             .collect(Collectors.toList());
index = files.indexOf(?);
英文:

I would like to get the first index of a string that contains a &quot;.txt&quot; in the list<String> using JAVA. without doing any loop. Because I have lots of value in File like :

[&quot;sample.txt&quot;, &quot;sample.csv&quot;,&quot;sample.docx&quot;,&quot;sample&quot;,&quot;sample.xlsx&quot;,&quot;sample2.txt, ...];

I only need the index of "sample.txt"

List&lt;String&gt; files = Arrays.asList(fileList).stream()
                             .map(x -&gt; 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&lt;String&gt; list = Arrays.asList(fileList);

String first = list.stream(fileList)
        .filter(x -&gt; x.endsWith(&quot;.txt&quot;)) // 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);

huangapple
  • 本文由 发表于 2020年8月17日 22:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63453268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定