Luciano Stupenengo
Luciano Stupenengo

Reputation: 183

Order a list of files by size in android

I have a code to get all the files in a directory into a list. Now I want to sort this list by size from smallest to biggest.

Is there a function or something to do this that's more efficient than writing my own code? If nothing exists, is there an efficient code out there you could point me to?

My code is:

private List<File> getListFiles(File parentDir) {
        ArrayList<File> inFiles = new ArrayList<>();
        File[] files = parentDir.listFiles();
        for (File file : files) {
            if (!file.getName().endsWith(".nomedia")) {
                inFiles.add(file);
            }
        }

        //Here I should write my sorting code


        return inFiles;
    }

Upvotes: 1

Views: 1778

Answers (4)

nasch
nasch

Reputation: 5498

You could also just pass a Comparator to a SortedSet.

Upvotes: 0

Luciano Stupenengo
Luciano Stupenengo

Reputation: 183

This code works. I used Array.sort to sort the file array before loading it to a List.

Had to look for some example on the comparator, since I had never used one.

private ArrayList<File> getListFiles(File parentDir) {
        ArrayList<File> inFiles = new ArrayList<>();
        File[] files = parentDir.listFiles();

        //Added Arrays.sort
        Arrays.sort(files, new Comparator<File>(){
            public int compare(File f1, File f2)
            {
                return Long.valueOf(f1.length()).compareTo(f2.length());
            } });


        for (File file : files) {
            if (!file.getName().endsWith(".nomedia")) {
                inFiles.add(file);
            }
        }
        return inFiles;
    }

Upvotes: 0

vdelricco
vdelricco

Reputation: 759

One way I see to do this would be to create a Hashmap of Files and their respective sizes and another Arraylist of just file sizes.

Hashmap myHashmap = new Hashmap<long, File>;

Insert each file into the hashmap like:

for (File file : inFiles) {
    myHashmap.put(file.length(), file);
    myFilesizeArrayList.add(file.length());
}

Then you can use the sort method of the ArrayList to sort the file sizes:

myFilesizeArrayList.sort();

Then turn the sorted filesize ArrayList back into a sort File ArrayList using the hashmap:

inFiles.clear();
for (long size : myFilesizeArrayList) {
    inFiles.add(myHashmap.get(size));
}

That should give you a sorted list of Files by size.

All that being said, I don't know if that's more efficient than just writing your own simple sorting algorithm. I would tend to just write my own as it would be a relatively trivial task.

Upvotes: 1

Substitut
Substitut

Reputation: 403

You can use the SizeFileComparator from commons io

It's really simple to use and provide lot of others useful class and methods.

Upvotes: 1

Related Questions