nnn
nnn

Reputation: 1037

Is this how to implement ascending sort when the comparator sorts descending?

Is this how to implement ascending sort when the comparator sorts descending?

// Sorts the emails alphabetically by subject in ascending order.
public void sortBySubjectAscending()
{
Collections.sort(emails, Collections.reverseOrder(new Email.SubjectDescendingComparator()));
}

Upvotes: 0

Views: 211

Answers (3)

dfb
dfb

Reputation: 13289

At the risk of being "that StackOverflow guy"...... :)

From http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#reverseOrder%28%29

public static Comparator reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering > on a collection of objects that implement the Comparable interface. (The natural ordering is the ordering imposed by the objects' own compareTo method.) This enables a simple idiom for sorting (or maintaining) collections (or arrays) of objects that implement the Comparable interface in reverse-natural-order.

It's educational to think about how you would implement this yourself, compareTo returns an int, all you need to do is invert the result....

Upvotes: 1

ratchet freak
ratchet freak

Reputation: 48216

yes this is a good solution

personally I'd have a comparator be a static member so you don't need to reinitialize it each time you want to sort and have Email also be able to give a ascendingComparator

public class Email{

    private static class SubjectDescendingComparator implements Comparable<Email>{
        //...
    }

    private static final Comparable<Email> subjectDescendingComparator =new SubjectDescendingComparator();
    private static final Comparable<Email> subjectAcendingComparator = Collections.reverseOrder(subjectDescendingComparator);


    public static Comparable<Email> getDecendingSubjectComparator{
        return subjectDescendingComparator;
    }


    public static Comparable<Email> getAcendingSubjectComparator{
        return subjectAcendingComparator;
    }


}

Upvotes: 0

dogbane
dogbane

Reputation: 274720

Yes, it does. If you reverse a descending comparator, you get an ascending comparator.

To break it down, this is what you are doing:

Comparator ascending = Collections.reverseOrder(new Email.SubjectDescendingComparator());
Collections.sort(emails, ascending);

Upvotes: 2

Related Questions