[英]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"...... :) 冒着被“那个StackOverflow家伙”的风险……:)
From http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#reverseOrder%28%29 来自http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#reverseOrder%28%29
public static Comparator reverseOrder() 公共静态比较器reverseOrder()
Returns a comparator that imposes the reverse of the natural ordering > on a collection of objects that implement the Comparable interface. 返回一个比较器,该比较器在实现Comparable接口的对象集合上强加自然顺序>的逆向。 (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. (自然顺序是由对象自己的compareTo方法强加的顺序。)这为用于以反向自然顺序实现(实现)Comparable接口的对象的集合(或数组)排序(或维护)的简单习惯用法。
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.... 考虑如何自己实现此方法很有教育意义,compareTo返回一个int,您要做的就是将结果求逆。
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 我个人将比较器设为静态成员,因此您无需在每次要排序时都重新初始化它,并且让Email能够提供一个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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.