Search code examples
javasortingcompareto

Sort ignoring punctuation (Java)


I am trying to sort an Android ListView object. I am currently using the following code:

  // Sort terms alphabetically, ignoring case
  adapter.sort(new Comparator<String>() {
        public int compare(String object1, String object2) {
            return object1.compareToIgnoreCase(object2);
        };

This sorts my list, whist ignoring case. However, it would be nice to ignore punctuation as well. For example:

c.a.t.
car
cat

should be sorted as follows:

car
c.a.t.
cat

(It doesn't actually matter which of the two cats (cat or c.a.t.) comes first, so long as they're sorted next to one another).

Is there a simple method to get around this? I presume the solution would involve extracting JUST the alphanumeric characters from the strings, then comparing those, then returning them back to their former states with the non-alphanumeric characters included again.


Solution

  • When you compare, remove the characters you don't care about

    public int compare(String str1, String str2) {
        String remove = "[\\.:',]"; // change this to all to characters to remoce
        return str1.replaceAll(remove, "").compareToIgnoreCase(object2.replaceAll(remove, ""));
    };