Java如何将File对象的列表转换为Path对象的列表?

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

Java how to convert List of File objects to List of Path objects?

问题

我正在构建一个库,用户已经有处理路径数组的代码。我有以下代码:

Collection<File> filesT = FileUtils.listFiles(
    new File(dir), new RegexFileFilter(".txt"), 
    DirectoryFileFilter.DIRECTORY
);

我在整个过程中使用了文件对象的列表,但我需要一种将 filesT 转换为 List<Path> 的方法。是否有一种快速的方法,也许是使用 lambda 将一个列表快速转换为另一个列表?

英文:

I am building a library for which the user already has code that processes an array of Paths.
I have this:

Collection&lt;File&gt; filesT = FileUtils.listFiles(
            new File(dir), new RegexFileFilter(&quot;.txt$&quot;), 
            DirectoryFileFilter.DIRECTORY
          );

I use the List of File object throughout but needed a way to convert filesT to List&lt;Path>.
Is there a quick way, maybe lambda to quickly convert one list to the other?

答案1

得分: 2

如果您有一个 Collection<File>,您可以使用 File::toPath 方法引用将其转换为 List<Path>Path[]

public List<Path> filesToPathList(Collection<File> files) {
    return files.stream().map(File::toPath).collect(Collectors.toList());
}

public Path[] filesToPathArray(Collection<File> files) {
    return files.stream().map(File::toPath).toArray(Path[]::new);
}
英文:

If you have a Collection&lt;File&gt;, you can convert it to List&lt;Path&gt; or to Path[] using File::toPath method reference:

public List&lt;Path&gt; filesToPathList(Collection&lt;File&gt; files) {
    return files.stream().map(File::toPath).collect(Collectors.toList());
}

public Path[] filesToPathArray(Collection&lt;File&gt; files) {
    return files.stream().map(File::toPath).toArray(Path[]::new);
}

答案2

得分: 2

我同意Alex Rudenko的回答,不过toArray()会需要一个转换。我提供一个替代方案(我会这样实现,返回不可变集合):

Set<Path> mapFilesToPaths(Collection<File> files) {
    return files.stream().map(File::toPath).collect(Collectors.toUnmodifiableSet());
}
英文:

I agree with Alex Rudenko's answer, however the toArray() would require a cast. I present an alternative (how I would implement, returning immutable collections):

Set&lt;Path&gt; mapFilesToPaths(Collection&lt;File&gt; files) {
    return files.stream().map(File::toPath).collect(Collectors.toUnmodifiableSet());
}

huangapple
  • 本文由 发表于 2020年10月14日 04:09:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64342475.html
匿名

发表评论

匿名网友

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

确定