Search code examples
androidsortingandroid-listviewandroid-actionbarlistadapter

How can I sort my ListView by Z-A alphabetical instead of A-Z?


The code below is what I use to order my ListView by alphabetical order:

 case R.id.menu_order_name:
    adapter.sort(new Comparator<Shop>() {
        @Override
        public int compare(Shop arg0, Shop arg1) {
            return arg0.getName().compareTo(arg1.getName());
        }
    });
    this.setListAdapter(adapter);
    adapter.notifyDataSetChanged();
    return true;

When I click it once it sorts by A-Z, although when I click the ActionBar menu option again to sort, I would like it to sort by Z-A. Can anybody show me how to reverse the order of the sort?

Thanks in advance, all help would be greatly appreciated!


Solution

  • Have a look at the documentation of String.compareTo():

    Returns
    0 if the strings are equal, a negative integer if this string is before the specified string, or a positive integer if this string is after the specified string.

    In other words: the short answer is to invert the values currently returned by your Comparator. The quickest way to do that would be to simply multiply by -1, because:

    -1 * -1 =  1
     0 * -1 =  0
     1 * -1 = -1
    

    That will effectively reverse the sorting order with respect to the original Comparator. In code:

    adapter.sort(new Comparator<Shop>() {
        @Override public int compare(Shop arg0, Shop arg1) {
            return -arg0.getName().compareTo(arg1.getName());
        }
    });
    

    However, since this is a quite common use case, we can do it even easier by leveraging functionality Java provides. Lets say the original Comparator is denoted by aToZComparator; we can reverse it using the Collections utilities:

    adapter.sort(Collections.reverseOrder(aToZComparator);
    

    This will basically apply the same concept of inverting the comparison result, and effectively change your aToZComparator to a zToAComparator.

    I'll leave it up to yourself to figure out the logic of when to choose which Comparator.