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

1.7k views Asked by At

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?

2

There are 2 answers

1
Nowhere Man On BEST ANSWER

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);
}
0
Jim Newpower On

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