TheLettuceMaster
TheLettuceMaster

Reputation: 15744

From Sorting Arrays of Objects to ArrayList<Object>

I had this:

Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
                public int compare(Item a, Item b) {
                    String newA = a.name.replaceAll("(?i)^the\\s+", "");
                    String newB = b.name.replaceAll("(?i)^the\\s+", "");
                    return newA.compareToIgnoreCase(newB);
                }
            };

Array.sort(MyItemArrayOfObjects, ignoreLeadingThe);

I stopped using Arrays and am now using ArrayList. So when I do this:

Collections.sort(MyItemArrayListOfObjects, ignoreLeadingThe);

I can't even figure out the pattern that it is now sorting by. Can I do a clean switch like this? (It is entirely possible I broke this with something not mentioned above, if this is right, then that's all I need to know)

Note: Originally, with the Arrays I was simply trying to alphabetize a list and ignore the leading "The". It's for an Android app. Each List row Item data was wrapped in an Object that I am passing to an ArrayAdapter. I simply wanted to take an ArrayList inside that object and alphabetize it. So essentially, it's an ArrayList with a few ArrayList inside it.

Upvotes: 3

Views: 167

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

It would work perfectly well for Collections.sort, I only suggest to improve the Comparator

    Comparator<Item> ignoreLeadingThe = new Comparator<Item>() {
        Pattern pattern = Pattern.compile("(?i)^the\\s+");
        public int compare(Item a, Item b) {
            String newA = pattern.matcher(a.name).replaceAll("");
            String newB = pattern.matcher(b.name).replaceAll("");
            return newA.compareToIgnoreCase(newB);
        }
    };

Upvotes: 1

Vitaly
Vitaly

Reputation: 2800

Your comparator looks good

The bad news is that it does not cache the resulting strings. So your sorting will create o(N*log(N)) Pattern's, Matcher's and String's objects not talking about the fact creation of some of them is not super fast.

UPD

It's advisable to use @Override on the methods you implement for interfaces and override in subclasses.

Upvotes: 1

Related Questions