I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?
![]() ![]() ![]() |
For completeness: |
|||
![]() ![]() |
If I remember correctly, the Arrays.sort(...) takes a Comparator<> that it will use to do the sorting. You can provide an implementation of it that looks at the extension part of the string. |
||
![]() ![]() |
You can implement a custom Comparator of Strings. Make it sort them by the substring after the last index of
|
|||
![]() ![]() |
Create a Comparator and compare the string extensions. Take a look at the following http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html Then pass in your List of strings to Arrays.sort(List, Comparator) |
||
![]() ![]() |
Create your own Comparator that treats the strings as filenames and compares them based on the extensions. Then use Arrays.sort with the Comparator argument. |
||
![]() ![]() |
I think the simplest thing you can do that also works when the filenname does not have a "." is to just reverse the names and compare them.
Its a shame that java's string does not even have a reverse(). |
||
![]() ![]() |
Comparators are often hard to get exactly right, and the comparison key has to be generated for every comparison which for most sorting algorithms mean O(n log n). Another approach is to create (key, value) pairs for each item you need to sort, put them in a TreeMap, and then ask for the values as these are sorted according to the key. For instance
prints out [#1, #2, #3] You should easily be able to adapt the key calculation to your problem. This only calculates the key once per entry, hence O(n) - (but the sort is still O(n log n)). If the key calculation is expensive or n is large this might be quite measurable. |
|||