Search code examples
javaandroidsortingcomparable

Using Comparable Inteface for sorting both Ascending and Descending


I have a class called NewsItem in my project. I want to sort an ArrayList of NewsItem in both ways Descending and Ascending as the user wants. Problem is I am using Comparable interface and I either return an int with Ascending condition or Descending condition and the other one is commented. How can I tell the Collections.sort() method to give me Ascending or Descending sorted List. Here's my code.

@Override
public int compareTo(NewsItem compNews) {
    int compTime=((NewsItem )compNews).getNewsTime();
    /* For Ascending order*/
    return this.NewsTime-compTime;

    /* For Descending order do like this */
    //return compTime-this.NewsTime;
}

Now here Descending one is commented so I can use one of it. I could use a static boolean in this class to either use one of these conditions. But since i'm serializing this class, I have not used any static variables in this class and have refrained from doing so. Any help is appreciated.


Solution

  • You class should have only 1 natural order. But this doesn't mean that a list of your class should have the same order.

    When sorting your list using Collections.sort, you can also pass a comparator that changes how this sort method sees your class.

    An example:

    Collections.sort(yourList, new Comparator<NewsItem>(){
        public void compare(NewsItem o1, NewsItem o2) {
            return o2.compareTo(o1);
        }
    });
    

    This instructs the sorting method to do the reverse of the method implemented in the main class.

    Notice that when Java 8 comes out for android, you can use the shorter Collections.sort(yourList, Comparator.reverseOrder()) instead.