Sunday, December 9, 2012

Sorting 2 columns in an Pojo class

When I was about to off, there is one late change requirement which need to be done before next day morning. User want the data to be sort rather than just leave it wild. Not there yet, the sort criteria has to be done on two columns. Graphic below shows the work need to be done. Take note that null value must be in the first place.



I know this could be done by using the sort method from Collections class, but my experience is only on one column sort, but I'm not sure whether the sort method is smart enough to handle my requirement. My logic thinking shows that if Column A is sorted, then I further sort on column B. In the same time I was thinking to write a custom bubble sort to cater for this requirement, but it was already late night. Without further thinking, I choose to challenge sort method (>.<*), and I come out this code:
public void sorting(ArrayList< mypojo > theList) {
  
  Collections.sort(theList, new Comparator< mypojo >(){

    @Override
    public int compare(MyPojo o1, MyPojo o2) {
    
      if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) < 0 ) {
        return -1;
      }
      else if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) == 0 ) {
        if( o1.getColumnB() == null || o2.getColumnB() == null ) {
          return 1;
        }
        else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) < 0 ) {
          return -1;
        }
        else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) > 0 ) {
          return 1;
        }
        else {
          return 0;
        }
      }
      else {
        return 1;
      }
    }
  });
}

And it works like charm. :o)

No comments: