In this section we will be showing source code on how to list files in ascending or descending order by filename. We will be using extensively the Collections class sort method. Calling the Collections.sort with only with one argument which is list, the list is sorted by default in ascending order. However if a comparator is placed as the second argument of the sort method, it will take into precedence that sorting method is relying on the logic of the comparator. Since we are only interested in getting the list sorted into ascending or descending order we will not be showing on how to use a custom comparator. Instead we will only be using the reverseOrder order method of the Collections class. This method returns a comparator which sorted the input list into descending order.

One notable method use on this source code is the usage of Arrays.asList method which convert array into list. We used this since we are taking into account the usage of Collections.sort method which takes List as an input parameter.

Java : Source code to sort filenames into descending or descending

Sample output