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?
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);
}
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.