mr. Holiday
mr. Holiday

Reputation: 1800

Java 8, Convert file name array to file array

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

Upvotes: 8

Views: 3337

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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]);

Upvotes: 9

Related Questions