In Java 8 you can do this:
strList.stream().map(File::new).collect(Collectors.toList())
More 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 Stream
from the list. Stream
is the representation of a collection of elements that supports operations throughout the set. It's something like SQL or jQuery.
Then, the map
of Stream
method lets you apply an operation to the whole set. The operation we want to perform is to convert a String
to a File
. We do this by passing a method that does the conversion of a single element and the map
method takes care of applying to all elements.
We could use a lambda method like this:
List<File> fileList = strList.stream().map(s -> new File(s)).collect(Collectors.toList());
However, we can simplify this by passing the reference to the constructor of File
which receives a String
.
Note that we could pass any method that receives a String
as a parameter and returns a File
and we would get the same result.
Finally, we get the result of the map
processing, which transformed a Stream
of String
into a Stream
of File
and collected it in a File usando o método
collect list and informing which type of% data structure we want.
Are you sure you want File
?
Since Java 7 it is recommended to use the new input and output API (NIO or New IO). So instead of using File
you should be using Path
.
Example:
List<Path> fileList = strList.stream().map(Paths::get).collect(Collectors.toList());