In Java 8 you can do so:
strList.stream().map(File::new).collect(Collectors.toList())
Most complete example:
List<String> strList = new ArrayList<>();
//adiciona itens em strList
List<File> fileList = strList.stream().map(File::new).collect(Collectors.toList());
Explanation
First, strList.stream()
generates a Stream
from the list. Stream
is the representation of a collection of elements that supports operations across the set. It is something like SQL or jQuery.
Then the method map
of Stream
allows you to apply an operation to the whole set. The operation we want to perform is to convert a String
for a File
. We do this by passing a method that converts a single element and the method map
takes care to apply to all elements.
We could use a lambda method as follows:
List<File> fileList = strList.stream().map(s -> new File(s)).collect(Collectors.toList());
However, we can simplify this by passing the reference to the File
who receives a String
.
Note that we could pass any method that receives a String
as parameter and return a File
and get the same result.
Finally, we took the result of processing map
, that transformed a Stream
of String
in a Stream
of File
and collected on a list of File usando o método
Collect` and stating what kind of data structure we want.
Are you sure you want to File
?
Since Java 7 it is recommended to use the new input and output API (NIO or New IO). Therefore, instead of using File
you should be using Path
.
Example:
List<Path> fileList = strList.stream().map(Paths::get).collect(Collectors.toList());