How do I sort file names by their extension?

To sort file names by their extension we can use the ExtensionFileComparator class from the Apache Commons IO library. This class provide a couple instances of comparator such as:

Comparator Description
EXTENSION_COMPARATOR Case sensitive extension comparator
EXTENSION_REVERSE Reverse case sensitive extension comparator
EXTENSION_INSENSITIVE_COMPARATOR Case insensitive extension comparator
EXTENSION_INSENSITIVE_REVERSE Reverse case insensitive extension comparator
EXTENSION_SYSTEM_COMPARATOR System sensitive extension comparator
EXTENSION_SYSTEM_REVERSE Reverse system sensitive path comparator

The following snippet show you how to use the first two comparators listed above.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FilenameUtils;
import static org.apache.commons.io.comparator.ExtensionFileComparator.*;

import java.io.File;
import java.util.Arrays;

public class FileSortByExtension {
    public static void main(String[] args) {
        File file = new File(".");

        // Excludes directory in the list
        File[] files = file.listFiles(File::isFile);

        if (files != null) {
            // Sort in ascending order.
            Arrays.sort(files, EXTENSION_COMPARATOR);
            FileSortByExtension.displayFileOrder(files);

            // Sort in descending order.
            Arrays.sort(files, EXTENSION_REVERSE);
            FileSortByExtension.displayFileOrder(files);
        }
    }

    private static void displayFileOrder(File[] files) {
        System.out.printf("%-20s | %s%n", "Name", "Ext");
        System.out.println("--------------------------------");
        for (File file : files) {
            System.out.printf("%-20s | %s%n", file.getName(),
                    FilenameUtils.getExtension(file.getName()));
        }
        System.out.println("");
    }
}

The result of the code snippet:

Name                 | Ext
--------------------------------
README               | 
lipsum.doc           | doc
lipsum.docx          | docx
data.html            | html
contributors.txt     | txt
pom.xml              | xml

Name                 | Ext
--------------------------------
pom.xml              | xml
contributors.txt     | txt
data.html            | html
lipsum.docx          | docx
lipsum.doc           | doc
README               | 

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

How do I sort files and directories based on their size?

In this example you will learn how to sort files and directories based on their size. Using the Apache Commons IO we can utilize the SizeFileComparator class. This class provides some instances to sort file size such as:

Comparator Description
SIZE_COMPARATOR Size comparator instance – directories are treated as zero size
SIZE_REVERSE Reverse size comparator instance – directories are treated as zero size
SIZE_SUMDIR_COMPARATOR Size comparator instance which sums the size of a directory’s contents
SIZE_SUMDIR_REVERSE Reverse size comparator instance which sums the size of a directory’s contents

Now let’s jump to the code snippet below:

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;

import static org.apache.commons.io.comparator.SizeFileComparator.*;

public class FileSortBySize {
    public static void main(String[] args) {
        File dir = new File(".");
        File[] files = dir.listFiles();

        if (files != null) {
            // Sort files in ascending order based on file size.
            System.out.println("Ascending order.");
            Arrays.sort(files, SIZE_COMPARATOR);
            FileSortBySize.displayFileOrder(files, false);

            // Sort files in descending order based on file size
            System.out.println("Descending order.");
            Arrays.sort(files, SIZE_REVERSE);
            FileSortBySize.displayFileOrder(files, false);

            // Sort files in ascending order based on file / directory
            // size
            System.out.println("Ascending order with directories.");
            Arrays.sort(files, SIZE_SUMDIR_COMPARATOR);
            FileSortBySize.displayFileOrder(files, true);

            // Sort files in descending order based on file / directory
            // size
            System.out.println("Descending order with directories.");
            Arrays.sort(files, SIZE_SUMDIR_REVERSE);
            FileSortBySize.displayFileOrder(files, true);
        }
    }

    private static void displayFileOrder(File[] files, boolean displayDirectory) {
        for (File file : files) {
            if (!file.isDirectory()) {
                System.out.printf("%-25s - %s%n", file.getName(),
                        FileUtils.byteCountToDisplaySize(file.length()));
            } else if (displayDirectory) {
                long size = FileUtils.sizeOfDirectory(file);
                String friendlySize = FileUtils.byteCountToDisplaySize(size);
                System.out.printf("%-25s - %s%n", file.getName(),
                        friendlySize);
            }
        }
        System.out.println("------------------------------------");
    }
}

In the code snippet above we use a couple method from the FileUtils class such as the FileUtils.sizeOfDirectory() to calculate the size of a directory and FileUtils.byteCountToDisplaySize() to create human readable file size.

The result of the code snippet:

Ascending order.
.editorconfig             - 389 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
------------------------------------
Descending order.
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
.editorconfig             - 389 bytes
------------------------------------
Ascending order with directories.
.editorconfig             - 389 bytes
src                       - 851 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
apache-commons-example    - 8 KB
hibernate-example         - 29 KB
.idea                     - 85 KB
------------------------------------
Descending order with directories.
.idea                     - 85 KB
hibernate-example         - 29 KB
apache-commons-example    - 8 KB
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
src                       - 851 bytes
.editorconfig             - 389 bytes

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

How do I sort an Enumeration?

package org.kodejava.example.util;

import java.util.*;

public class EnumerationSort {
    public static void main(String[] args) {
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        Random random = new Random();
        Vector<Integer> data = new Vector<Integer>();
        for (int i = 0; i < 10; i++) {
            data.add(Math.abs(random.nextInt()));
        }

        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally we sort the list using
        // Collections.sort() method.
        Enumeration enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        // Prints out all generated number after sorted.
        for (Integer number : list) {
            System.out.println("number = " + number);
        }
    }
}

An example result of the code above is:

number = 64029842
number = 72921309
number = 230054456
number = 256151404
number = 345486128
number = 387933255
number = 398974777
number = 626349261
number = 654063730
number = 1319397578

How do I sort files based on their last modified date?

This example demonstrates how to use Apache Commons IO LastModifiedFileComparator class to sort files based on their last modified date in ascending and descending order. There are two comparators defined in this class, the LASTMODIFIED_COMPARATOR and the LASTMODIFIED_REVERSE.

package org.kodejava.example.commons.io;

import static org.apache.commons.io.comparator.LastModifiedFileComparator.*;

import java.io.File;
import java.util.Arrays;

public class FileSortLastModified {
    public static void main(String[] args) {
        File dir = new File(System.getProperty("user.home"));
        File[] files = dir.listFiles();

        if (files != null) {
            // Sort files in ascending order based on file's last
            // modification date.
            System.out.println("Ascending order.");
            Arrays.sort(files, LASTMODIFIED_COMPARATOR);
            FileSortLastModified.displayFileOrder(files);

            System.out.println("------------------------------------");

            // Sort files in descending order based on file's last
            // modification date.
            System.out.println("Descending order.");
            Arrays.sort(files, LASTMODIFIED_REVERSE);
            FileSortLastModified.displayFileOrder(files);
        }
    }

    private static void displayFileOrder(File[] files) {
        for (File file : files) {
            System.out.printf("%2$td/%2$tm/%2$tY - %s%n", file.getName(),
                file.lastModified());
        }
    }
}

Here are the example results produced by the code snippet:

Ascending order.
15/12/2016 - ntuser.dat.LOG1
15/12/2016 - ntuser.ini
15/12/2016 - .m2
18/12/2016 - Contacts
22/12/2016 - Videos
01/01/2017 - VirtualBox VMs
02/01/2017 - Desktop
02/01/2017 - Documents
------------------------------------------
Descending order.
02/01/2017 - Documents
02/01/2017 - Desktop
01/01/2017 - VirtualBox VMs
22/12/2016 - Videos
18/12/2016 - Contacts
15/12/2016 - .m2
15/12/2016 - ntuser.ini
15/12/2016 - ntuser.dat.LOG1

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

How do I sort items in a Set?

The trick to sort a java.util.Set is to use the implementation of a java.util.SortedSet such as the java.util.TreeSet class. The example below shows you the result of using the java.util.TreeSet class, in which the items in it will be sorted based on the element’s natural order.

package org.kodejava.example.util;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        // The TreeSet class is an implementation of a SortedSet, this means
        // that when your are using the TreeSet to store you data collections
        // you'll get the items ordered base on its elements natural order.
        Set<String> set = new TreeSet<String>();

        // In the example below we add some letters to the TreeSet, this mean
        // that the alphabets will be ordered based on the alphabet order
        // which is from A to Z.
        set.add("Z");
        set.add("A");
        set.add("F");
        set.add("B");
        set.add("H");
        set.add("X");
        set.add("N");

        for (String item : set) {
            System.out.print(item + " ");
        }
    }
}

This demo prints:

A B F H N X Z 

How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.example.util.support;

public class Person implements Comparable {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.name.compareTo(p.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Wayan");
persons[1] = new Person("Made");
persons[2] = new Person("Nyoman");
persons[3] = new Person("Ketut");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.example.util;

import org.kodejava.example.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String names[] = {"Wayan", "Made", "Nyoman", "Ketut"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person persons[] = new Person[4];
        persons[0] = new Person("Wayan");
        persons[1] = new Person("Made");
        persons[2] = new Person("Nyoman");
        persons[3] = new Person("Ketut");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Ketut, Made, Nyoman, Wayan]
Persons = [Ketut, Made, Nyoman, Wayan]

How do I sort elements of an array?

package org.kodejava.example.util;

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // An array of random numbers
        int numbers[] = {3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55};
        System.out.println("Before: " + Arrays.toString(numbers));

        // We need to sort these array elements into a correct order
        // from the smallest to the greatest. We will use the Arrays
        // class on java.utils package to do the sort. The sort
        // method of this class are overloaded, so they can take
        // other type of array as well such as byte[], long[],
        // float[], Object[].
        Arrays.sort(numbers);
        System.out.println("After : " + Arrays.toString(numbers));

        // We can also do the sort only for the specified range of
        // array elements.
        float money[] = {1.05f, 99.8f, 3f, 4.55f, 7.23f, 6.50f};
        Arrays.sort(money, 3, money.length);

        // Here we display the sort result, the first and the second
        // element of the array is not included in the sort process.
        System.out.println("Money : " + Arrays.toString(money));
    }
}

And here are the results:

Before: [3, 1, 8, 34, 1, 2, 13, 89, 5, 21, 55]
After : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Money : [1.05, 99.8, 3.0, 4.55, 6.5, 7.23]