Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NaturalComparator implements Comparator { // use generic objects and .toString() to support File etc
- public int compare(Object f1, Object f2) {
- // split *between* the transition from digits to non-digits & vice-versa
- String[] s1 = f1.toString().split("(?<!\\d)(?=\\d)|(?<=\\d)(?!\\d)");
- String[] s2 = f2.toString().split("(?<!\\d)(?=\\d)|(?<=\\d)(?!\\d)");
- int c = 0;
- for (int i = 0; i < s1.length && i < s2.length; i++)
- {
- // there are non-digits or the digits are the same length
- if (s1[i].length() == s2[i].length() || s1[i].matches("\\D") || s2[i].matches("\\D"))
- c = s1[i].compareTo(s2[i]);
- else
- c = s1[i].length() > s2[i].length() ? 1 : -1;
- if (c != 0)
- return c;
- }
- return s1.length == s2.length ? 0 : s1.length > s2.length ? 1 : -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement