8

I have an array of String file names and I want to convert them into File array. I am wandering whether there is a more elegant way of doing it rather than this one.

String[] names = {file1, file2, file3};
File[] files = new String[names.length];
for (int i = 0; i < names.length; i++) {
   files[i] = new File(names[i]);
} 

EDIT Thanks for noting in comments. I am using Java 8

3
  • 5
    Are you using java 8? Commented Sep 2, 2015 at 14:46
  • 1
    Java-8 similar: stackoverflow.com/questions/23057549/… Commented Sep 2, 2015 at 14:47
  • 1
    Side note: Consider to use Path from the NIO.2 File API instead of File objects. Commented Sep 2, 2015 at 15:05

1 Answer 1

9

In Java 7 or less, using plain JDK, there's not. Since Java 8, you may use streams for this:

String[] names = {file1, file2, file3};
File[] files = Arrays.stream(names)
    .map(s -> new File(s))
    .toArray(size -> new File[names.length]);
Sign up to request clarification or add additional context in comments.

4 Comments

s -> new File(s) can be simplified to File::new. Personally, I prefer method references.
@bcsb1001 careful when using that approach, specially for overloaded methods. After some reading and facing issues using Class::method when method is overloaded (even class constructors), I prefer to use the descriptive way.
You can also use .toArray(File[]::new), but again: consider Path instead of File and possibly List instead of array.
@Puce I'm aware of that, but OP asked about using File and arrays. Just providing what he asked.

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.