问题描述
我正在建立一个库,用户已经为它提供了处理一系列Path的代码。 我有这个:
PHP artisan serve --host=IP-Address --port=8001
我始终使用“文件列表”对象,但是需要一种将filesT转换为“ 列表 ”的方法。 有没有一种快速的方法,也许是lambda,可以将一个列表快速转换为另一个列表?
解决方法
如果您有Collection<File>
,则可以使用List<Path>
方法参考将其转换为Path[]
或File::toPath
:
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);
}
,
我同意亚历克斯·鲁登科的回答,但是toArray()需要强制转换。我提出了一个替代方案(如何实现,返回不可变的集合):
Set<Path> mapFilesToPaths(Collection<File> files) {
return files.stream().map(File::toPath).collect(Collectors.toUnmodifiableSet());
}