Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NaturalComparator implements Comparator<File> {
- public int compare(File f1, File f2) {
- String[] s1 = f1.getName().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); // split *between* the transition from digits to non-digits & vica-versa
- String[] s2 = f2.getName().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
- int c = 0;
- for (int i = 0; i < s1.length && i < s2.length; i++)
- try {
- c = new Long(s1[i]).compareTo(Long.parseLong(s2[i]));
- }
- catch (NumberFormatException nfe) {
- c = s1[i].compareTo(s2[i]);
- }
- finally {
- if (c != 0)
- return c;
- }
- return s1.length > s2.length ? 1 : 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement