简体   繁体   中英

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()));
}

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);

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....

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;
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM