Jayababu
Jayababu

Reputation: 1621

Convert List of File[] into File[]

I have List of File[] like this.

 List<File[]> fileList = new ArrayList<File[]>();

I need to convert it into a File[] something like this File[] finalFiles.

Is there any way that we can convert Array of Files[] into a Single File[]

Upvotes: 1

Views: 1421

Answers (3)

Dbs Ray
Dbs Ray

Reputation: 1

This works perfectly:

File[] finalFiles = (File[]) fileList.toArray(new File[fileList.size()]);

Upvotes: 0

GoneUp
GoneUp

Reputation: 385

Java 7 Solution:

        List<File[]> fileList = new ArrayList<File[]>();
        int count = 0;
        for (int i = 0; i < fileList.size(); i++){
            count += fileList.get(i).length;
        }

        File[] finalFiles = new File[count];
        int pointer = 0;
        for (int i = 0; i < fileList.size(); i++){
            System.arraycopy(fileList.get(i), 0, finalFiles, pointer, fileList.get(i).length);
            pointer += fileList.get(i).length;
        }

Upvotes: 2

Tunaki
Tunaki

Reputation: 137084

Using the Stream API, you could have:

File[] finalFiles = fileList.stream().flatMap(Arrays::stream).toArray(File[]::new);

This creates a stream where each element is an array of files (Stream<File[]>), flat maps each array of files (so we have a Stream<File>) and makes a new array of all the elements.

Upvotes: 4

Related Questions