英文:
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<File> filesT = FileUtils.listFiles(
new File(dir), new RegexFileFilter(".txt$"),
DirectoryFileFilter.DIRECTORY
);
I use the List of File object throughout but needed a way to convert filesT to List<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<File>
, you can convert it to List<Path>
or to Path[]
using File::toPath
method reference:
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);
}
答案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<Path> mapFilesToPaths(Collection<File> files) {
return files.stream().map(File::toPath).collect(Collectors.toUnmodifiableSet());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论