2

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?

4
  • 1
    And how did you mean to create a Path object from a File object? Commented Oct 13, 2020 at 20:14
  • To be clear, is the conversion from java.io.File to java.nio.file.Path? Commented Oct 13, 2020 at 20:16
  • Possibly related: Get java.nio.file.Path object from java.io.File Commented Oct 13, 2020 at 20:16
  • 2
    Why don’t you use Path in the first place? Getting a filtered list, including pattern matching, is already provided by the API. Commented Oct 14, 2020 at 11:22

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry late response but this is how I did what I needed to do. I actually used Jim Newpower's Set<Path> type from above. So technically you both have the answer. Thank guys.
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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.