How to get a string arraylist value, for an array of File

0

I have a job to do, to do it, I need to pass an information from an array composed of strings (which are the paths) to an array of files so that I can read those paths, value directly in these two ways

leitura.add(System.out.println(Arrays.toString(diretorioRaiz.toArray()) ));// 1 tentativa
leitura.addAll(diretorioRaiz.get(0));//2 tentativa

I did this, but I could not, I also tried to create a variable of type string to "hold" the value and then use it to get the value

static  String myString = new String ();
myString = diretorioRaiz.get(0);
leitura.add(myString);
    
asked by anonymous 03.11.2015 / 02:56

2 answers

1

If you have a ArrayList of strings, just go through it and use the "string of the time" to create a new File(String pathname) :

ArrayList<String> arrayListDeStrings = ...

// Populando 'arrayListDeStrings'.


ArrayList<File> arrayListDeFiles = new ArrayList<>();

for(String stringDaVez : arrayListDeStrings)
   arrayListDeFiles.add(new File(stringDaVez));
    
03.11.2015 / 03:19
1

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());
    
03.11.2015 / 06:03