Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 336
mr. Holiday Avatar asked Sep 02 '15 14:09

mr. Holiday


1 Answers

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]);
like image 154
Luiggi Mendoza Avatar answered Nov 02 '22 03:11

Luiggi Mendoza