1

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?

Mike
  • 43
  • 8

2 Answers2

2

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);
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Sorry late response but this is how I did what I needed to do. I actually used Jim Newpower's Set type from above. So technically you both have the answer. Thank guys. – Mike Oct 28 '20 at 12:38
2

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());
}
Jim Newpower
  • 116
  • 5