How to take a string arraylist value, for a File array

Asked

Viewed 964 times

0

I have a job to do, to do it, I need to pass information from an array composed of strings (which are the paths) to an array of files for reading these paths, I tried to get the value directly from these two forms

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

I did this, but I couldn’t, I also tried to create a string type variable to "hold" the value and then use it to pick the value

static  String myString = new String ();
myString = diretorioRaiz.get(0);
leitura.add(myString);

2 answers

1

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étodoCollect` 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());

1

If you have a ArrayList of strings, just scroll through it and use the "turn string" 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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.