【问题标题】:Get index that contains ".txt" in the list without using loop in JAVA在不使用 JAVA 循环的情况下获取列表中包含“.txt”的索引
【发布时间】:2020-08-17 14:47:28
【问题描述】:

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

【问题讨论】:

  • 既然你已经在使用流了,为什么不试试使用 filter 和 findFirst 呢?
  • fileList 的类型是什么?

标签: java arrays list java-stream indexof


【解决方案1】:

您是否要使用:

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

【讨论】:

  • 这就是我要找的。非常感谢!
猜你喜欢
  • 2020-08-25
  • 2021-10-09
  • 2020-04-30
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
相关资源
最近更新 更多