2015-09-02 49 views
7

我有一個String文件名的數組,我想將它們轉換成File陣列。我徘徊是否有一個更優雅的做法,而不是這一個。Java 8,轉換文件名陣列到文件陣列

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

編輯 感謝您的意見值得注意。我正在使用Java 8

+5

您是否正在使用java 8? – wjans

+1

Java-8類似:http://stackoverflow.com/questions/23057549/lambda-expression-to-convert-array-list-of-string-to-array-list-of-integers – BackSlash

+1

附註:考慮使用來自NIO.2 File API的路徑,而不是File對象。 – Puce

回答

6

在Java 7或更低版​​本中,使用普通的JDK,沒有。從Java 8開始,您可以使用以下流:

String[] names = {file1, file2, file3}; 
File[] files = Arrays.stream(names) 
    .map(s -> new File(s)) 
    .toArray(size -> new File[names.length]); 
+2

儘管如此,OP的代碼對我來說更具可讀性: - | +1 –

+3

's - > new File(s)'可以簡化爲'File :: new'。就個人而言,我更喜歡方法參考。 – bcsb1001

+0

@ bcsb1001謹慎使用該方法時,特別適用於重載方法。在* method *被重載(甚至類構造函數)時,在使用'Class :: method'進行一些閱讀和麪對問題之後,我更喜歡使用描述性的方式。 –